·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> 触摸事件-拖动view

触摸事件-拖动view

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

案例:通过触摸事件拖动imageView和view1和view2

注意:1.imgeview默认不能响应触摸事件,2.视图有三个子视图,如何区分多个视图

用storyBoard托人2个view和一个imageView,IBOutlet连线

案例图片:

//让imageView接受用户触摸

1 [self.imageView setUserInteractionEnabled:YES];

区分哪个视图

1 [touch view] == self.imageView

 

触摸事件代码

 

 1 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
 2 {
 3     //1.获取用户点击
 4     UITouch *touch = [touches anyObject];
 5     CGPoint location = [touch locationInView:self.view];
 6     CGPoint PReLocation = [touch previousLocationInView:self.view];
 7     CGPoint dertPoint = CGPointMake(location.x - preLocation.x, location.y - preLocation.y);
 8     //2.判断点击了那个视图
 9     if ([touch view] == self.imageView) {
10         NSLog(@"点击了图像");
11         
12         [self.imageView setCenter:CGPointMake(self.imageView.center.x + dertPoint.x, self.imageView.center.y + dertPoint.y)];
13     }else if ([touch view] == self.redView){
14         NSLog(@"点击了 hongse");
15         [self.redView setCenter:CGPointMake(self.redView.center.x + dertPoint.x, self.redView.center.y + dertPoint.y)];
16         
17     }else if ([touch view] == self.greenView){
18         //提示最好不要直接用else处理,因为随时有可能添加新的控件
19         NSLog(@"点击 green");
20         [self.greenView setCenter:CGPointMake(self.greenView.center.x + dertPoint.x, self.greenView.center.y + dertPoint.y)];
21     }
22     
23 }