IOS拖拽View移动
工程中经常有这样的需求, 拖拽一个View进行移动, 当拖动结束的时候进行, 需要做一些其它操作
这时候用下面这个方法实现就很方便
直接上代码, 其实挺简单.
#import "TestViewController.h"
@interface TestViewController ()
{
CGPoint beginpoint;
}
@property (nonatomic, assign) BOOL isInView;
@property (nonatomic, strong) UIView *moveView;
@end
@implementation TestViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.moveView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, 200, 100)];
self.moveView.backgroundColor = [UIColor yellowColor];
[self.view addSubview: self.moveView];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (!self.isInView) // 仅当取到touch的view是小窗口时,我们才响应触控,否则直接return
{
return;
}
NSLog(@"我正在移动中");
UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView:self.moveView];
//偏移量
float offsetX = currentPosition.x - beginpoint.x;
float offsetY = currentPosition.y - beginpoint.y;
//移动后的中心坐标
self.moveView.center = CGPointMake(self.moveView.center.x + offsetX, self.moveView.center.y + offsetY);
//x轴左右极限坐标
if (self.moveView.center.x > (self.moveView.superview.frame.size.width-self.moveView.frame.size.width/2))
{
CGFloat x = self.moveView.superview.frame.size.width-self.moveView.frame.size.width/2;
self.moveView.center = CGPointMake(x, self.moveView.center.y + offsetY);
}
else if (self.moveView.center.x < self.moveView.frame.size.width/2)
{
CGFloat x = self.moveView.frame.size.width/2;
self.moveView.center = CGPointMake(x, self.moveView.center.y + offsetY);
}
//y轴上下极限坐标
if (self.moveView.center.y > (self.moveView.superview.frame.size.height-self.moveView.frame.size.height/2))
{
CGFloat x = self.moveView.center.x;
CGFloat y = self.moveView.superview.frame.size.height-self.moveView.frame.size.height/2;
self.moveView.center = CGPointMake(x, y);
}
else if (self.moveView.center.y <= self.moveView.frame.size.height/2)
{
CGFloat x = self.moveView.center.x;
CGFloat y = self.moveView.frame.size.height/2;
self.moveView.center = CGPointMake(x, y);
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"我开始移动了");
UITouch *touch = [touches anyObject];
//设置当接触的点在carBgView上面调用 此处设置当触摸的view的快读等于moveView的宽度时候调用
// if ((touch.view.frame.size.width < 180))也可以小于具体的一片区域
if ((touch.view.frame.size.width == self.moveView.frame.size.width)) {
self.isInView = YES;
}
else
{
self.isInView = NO;
}
beginpoint = [touch locationInView:self.moveView];
[super touchesBegan:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"我滑动结束了");
}
我这里是在viewController中实现的
也可以在view中实现这个功能
view中也有这三个方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event