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

UIGestureRecognizer手势 : 6-长按手势

长按手势(UILongPressGestureRecognizer)简介

通过长按手势(UILongPressGestureRecognizer)可以监控手势作用于UI控件的开始长按、长按过程中以及松开等状态,并且设置不同的动作。最常见的应用案例可以参考微信的对讲模式,按住按钮即可开始录音,松开后结束录音并发送给对方。长按手势一定需要和UIGestureRecognizer类的state属性进行配合使用,即通过不同状态state下,实现不同的功能。UIGestureRecognizer类的state属性中,常见的有:

  • UIGestureRecognizerStateBegan:开始手势事件
  • UIGestureRecognizerStateEnded:结束手势事件
  • UIGestureRecognizerStateChanged:手势位置发生变化
  • UIGestureRecognizerStateFailed:无法识别的手势

示例代码

下方的示例代码中,创建了一个UIImageView对象,并为其添加了一个长按手势,当用户按住该图片框对象时,可以监控到开始长按、长按过程中以及长按结束3个状态。

  • 创建一个Single View Application应用

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

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建UIView对象
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 250, 150, 150)];
    imageView.image = [UIImage imageNamed:@"99logo"];
    imageView.userInteractionEnabled = YES;
    [self.view addSubview:imageView];
    //长按手势
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [imageView addGestureRecognizer:longPressGesture];
}
  • 添加longPressGesture:方法,在该方法中根据gesture参数的state可以用于判断长按的状态。
-(void) longPress: (UILongPressGestureRecognizer *) gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        NSLog(@"长按开始");
    }else if (gesture.state == UIGestureRecognizerStateEnded){
        NSLog(@"长按结束");
    }
    else {
        NSLog(@"长按中");
    }
}

运行结果如下。

示例代码

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