对于我们在应用程序可能实现的所有常见手势,简单来说,需要创建一个UIGestureRecognizer
类的对象,或者是它的子类的对象。下面列出了”手势识别器类”:
- 轻按
UITapGestureRecognizer
:手指在屏幕上轻按 - 长按
UILongPressGestureRecognizer
:在屏幕上按住指定时间 - 张合
UIPinchGestureRecognizer
:张合对象以缩放对象 - 旋转
UIRotationGestureRecognizer
:沿圆形滑动两个手指 - 轻扫
UISwipeGestureRecognizer
:沿特定的方向轻扫 - 平移
UIPanGestureRecognizer
:触摸并拖曳
使用手势很简单,分为三步:
- 创建手势识别器对象实例。创建时,指定一个回调方法,当手势开始,改变、或结束时,执行回调方法。
- 设置手势识别器对象实例的相关属性(可选部分)
- 添加到需要识别的 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];
}
}