1.拖动手势简介拖动手势(UIPanGestureRecognizer)可以修改一个UI控件的位置,在有些游戏类App中比较常见。拖动事件发生时,通过translationInView:方法,可以得到一个CGPoint类型的返回值,即位置的偏移量,可以根据偏移量修改对应UI控件的center属性从而实现UI控件的位置移动效果。
- (CGPoint)translationInView:(nullable UIView *)view;
2.示例代码在下面的示例代码中,创建了一个UIImageView对象,并为其添加了一个拖动手势,用户可以把该UIImageView控件拖动到屏幕的任意位置。创建一个Single View Application应用。在ViewController.m文件中添加如下代码,该代码创建了拖动手势。
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. //创建UIImageView对象 UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 250, 150, 150)]; imageView.image = [UIImage imageNamed:@"logo"]; imageView.userInteractionEnabled = YES; [self.view addSubview:imageView]; //拖动手势 UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)]; [imageView addGestureRecognizer:panGesture]; }
添加pan:方法,实现UI控件位置更新操作。
- (void)pan: (UIPanGestureRecognizer *)gesture { NSLog(@"%s", __func__); //获取位置变化量translation CGPoint translation = [gesture translationInView:self.view]; gesture.view.center = CGPointMake(gesture.view.center.x + translation.x, gesture.view.center.y + translation.y); [gesture setTranslation:CGPointZero inView:self.view]; }
当用户拖动该控件时,pan:方法会被反复调用,如图8-73、图8-74所示。
图8-73 移动效果
运行结果
摘自《iOS开发:从零基础到精通》