UIGestureRecognizer手势 : 2-点击手势
UITapGestureRecognizer类能够识别点击手势,同时能够识别单击/双击,甚至能够识别到使用几根手指来进行点击。
UITapGestureRecognizer类介绍
UITapGestureRecognizer类可以用于创建识别点击手势,常用的属性包括:
- 需要点击的次数,用于识别单击或双击,默认为:单击
@property (nonatomic) NSUInteger numberOfTapsRequired;
- 点击的手指数,默认为:1
@property (nonatomic) NSUInteger numberOfTouchesRequired;
单个手指单击手势实现
下方的示例代码中,创建了一个UIView对象,并为其添加了一个点击手势,该点击手势只需要一个手指点击一次即可识别。
创建一个Single View Application应用
在ViewController.m文件中添加如下代码,该代码创建了点击手势
- (void)viewDidLoad {
[super viewDidLoad];
//创建UIView对象
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 250, 50)];
myView.backgroundColor = [UIColor redColor];
[self.view addSubview:myView];
//单击,单手指
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
//单击
singleTap.numberOfTapsRequired = 1;
//单手指
singleTap.numberOfTouchesRequired = 1;
//添加到myView
[myView addGestureRecognizer:singleTap];
}
- 实现单击手势触发后的调用的singleTap:方法
-(void)singleTap:(UITapGestureRecognizer *) tap {
NSLog(@"单个手势单击触发!");
}
运行结果如下,当我们点击显示在屏幕中的myView对象时,会执行singleTap:方法中的业务逻辑。
双手指双击手势实现
通过修改numberOfTapsRequired以及numberOfTouchesRequired两个属性,可以修改点击手势的实现方式。例如,对上述的代码进行修改后,可以实现只有当两个手指双击myView对象时,才能触发对应的业务逻辑。
- (void)viewDidLoad {
[super viewDidLoad];
//创建UIView对象
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 250, 50)];
myView.backgroundColor = [UIColor redColor];
[self.view addSubview:myView];
//双击双手指
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
//双击
doubleTap.numberOfTapsRequired = 2;
//双手指
doubleTap.numberOfTouchesRequired = 2;
//添加到myView
[myView addGestureRecognizer:doubleTap];
}
示例代码
https://github.com/99ios/8.4.2
文章发布时间为: August 8th , 2016 at 08:15 pm
最后编辑时间为: September 13th , 2017 at 02:55 pm
本文由 99ios 创作,转载请注明出处
最后编辑时间为: September 13th , 2017 at 02:55 pm
本文由 99ios 创作,转载请注明出处