iOS的触摸与手势识别

对于我们在应用程序可能实现的所有常见手势,简单来说,需要创建一个UIGestureRecognizer类的对象,或者是它的子类的对象。下面列出了”手势识别器类”:

  • 轻按UITapGestureRecognizer:手指在屏幕上轻按
  • 长按UILongPressGestureRecognizer:在屏幕上按住指定时间
  • 张合UIPinchGestureRecognizer:张合对象以缩放对象
  • 旋转UIRotationGestureRecognizer:沿圆形滑动两个手指
  • 轻扫UISwipeGestureRecognizer:沿特定的方向轻扫
  • 平移UIPanGestureRecognizer:触摸并拖曳

使用手势很简单,分为三步:

  1. 创建手势识别器对象实例。创建时,指定一个回调方法,当手势开始,改变、或结束时,执行回调方法。
  2. 设置手势识别器对象实例的相关属性(可选部分)
  3. 添加到需要识别的 View 中。每个手势只对应一个 View,当屏幕触摸在 View 的边界内时,如果手势和预定的一样,那就会执行回调方法。

手势状态枚举如下:

typedef NS_ENUM(NSInteger, UIGestureRecognizerState) {
2     UIGestureRecognizerStatePossible,   // 尚未识别是何种手势操作(但可能已经触发了触摸事件),默认状态
3     UIGestureRecognizerStateBegan,      // 手势已经开始,此时已经被识别,但是这个过程中可能发生变化,手势操作尚未完成
4     UIGestureRecognizerStateChanged,    // 手势状态发生转变
5     UIGestureRecognizerStateEnded,      // 手势识别操作完成(此时已经松开手指)
6     UIGestureRecognizerStateCancelled,  // 手势被取消,恢复到默认状态
7     UIGestureRecognizerStateFailed,     // 手势识别失败,恢复到默认状态
8     UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded // 手势识别完成,同UIGestureRecognizerStateEnded
9 };

实例代码:


@interface ViewController ()

@property(nonatomic,strong)UILongPressGestureRecognizer* longPress;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIButton* btn=[[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    [self.view addSubview:btn];
    btn.backgroundColor=[UIColor redColor];
    self.longPress =
    [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                  action:@selector(clickMe)];
    self.longPress.allowableMovement=NO;
    self.longPress.minimumPressDuration = 1;
    [btn addGestureRecognizer:self.longPress];

}

-(void)clickMe{
    if (self.longPress.state==UIGestureRecognizerStateBegan) {
        UIAlertAction* action=[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
        UIAlertController* alert=[UIAlertController alertControllerWithTitle:@"ok" message:@"ok" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值