IOS中触控事件一般是多点触控事件,加速计事件(翻译不太好),远程控制事件。在IOS中大量的手势识别苹果都已经给我们处理好了他们都在UIKit中,例如UIControl的子类UIButton,UISlider已经做好了手势的识别。触碰button能够触发事件,滑动slider触发事件。在IOS中的大部分控件都已经为我们做好了手势的识别,但是如果我们想要自己DIY一个控件有需要手势判断怎么办呢?好接下来进入正题开始Gesture Recognizers之旅。
Gesture recognizers 能够正确的判断出用户的手势如pinch(捏)、swipe(滑动)、旋转等。Gesture recognizers能够将底层的事件处理代码转换到高层次的
动作中。
示例代码:
#import "PMBViewController.h" @interface PMBViewController ()<UIGestureRecognizerDelegate>{ int count; } @property (weak, nonatomic) IBOutlet UILabel *label; @end @implementation PMBViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self.view addGestureRecognizer:[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture)]]; count = 0; } - (void)handleGesture{ count ++; self.label.text = [NSString stringWithFormat:@"%d",count]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
以下是Gesture recognizer 识别的手势
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self.view addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)]]; } - (void)handlePanGesture:(UIGestureRecognizer *)sender{ CGPoint point = [sender locationInView:self.view]; NSLog(@"X:%f Y:%f",point.x,point.y); }
Gesture recognizer classes of the UIKit framework
Gesture
UIKit class
Tapping (any number of taps)
UITapGestureRecognizer
Pinching in and out (for zooming a view)
UIPinchGestureRecognizer
Panning or dragging
UIPanGestureRecognizer
Swiping (in any direction)
UISwipeGestureRecognizer
Rotating (fingers moving in opposite directions)
UIRotationGestureRecognizer
Long press (also known as “touch and hold”)
UILongPressGestureRecognizer
由以上示例代码可知Gesture Recognizer需要依附于一个view,但view确可以有多个Gesture Recognizer,因为一个view可能需要相应多个不同的手势。