- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
利用以上方法,可实现对一个view进行拖拽
@interface ViewController : UIViewController
{
UIView *view1;
CGFloat setoffX;
CGFloat setoffY;
}
@end
- (void)viewDidLoad
{
[super viewDidLoad];
view1 = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
view1.backgroundColor = [UIColor redColor];
[self.view addSubview:view1];
}
#pragma -mark开始触摸时执行的方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"打印当前方法名%s",__FUNCTION__);
//获取一个触摸对象
UITouch *touch = [touches anyObject];
//获取当前点
CGPoint currentPoint = [touch locationInView:self.view];
setoffX = view1.center.x-currentPoint.x;
setoffY = view1.center.y-currentPoint.y;
}
#pragma -mark开始移动时执行的方法
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
//点击视图让它跟着走
if (touch.view == view1) {
view1.center = CGPointMake(currentPoint.x+setoffX, currentPoint.y+setoffY);
}
}
#pragma -mark触摸中断时执行的方法
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"触摸中断时执行的方法");
}
#pragma -mark触摸终止时执行的方法
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}