免费开源的iOS开发学习平台

UIGestureRecognizer手势 : 5-拖动手势

拖动手势简介

拖动手势(UIPanGestureRecognizer)可以修改一个UI控件的位置,在有些游戏类App中比较常见。拖动事件发生时,通过translationInView:方法,可以得到一个CGPoint类型的返回值,即位置的偏移量,可以根据偏移量修改对应UI控件的center属性从而实现UI控件的位置移动效果。

- (CGPoint)translationInView:(nullable UIView *) view; 

示例代码

下方的示例代码中,创建了一个UIImageView对象,并为其添加了一个拖动手势,用户可以把该UIImageView控件拖动到屏幕的任意位置。

  • 创建一个Single View Application应用

  • 在ViewController.m文件中添加如下代码,该代码创建了拖动手势

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建UIImageView对象
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 250, 150, 150)];
    imageView.image = [UIImage imageNamed:@"99logo"];
    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:方法会被反复调用。

示例代码

https://github.com/99ios/8.4.5