IOS手势处理

IOS手势处理

介绍

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);
}




Table 1-1  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可能需要相应多个不同的手势。


Gesture Trigger Action Messages

当gesture recognizer 识别出特定手势后他会给target发送action消息,因此在创建recognizer的时候他需要target和action来进行初始化。
在IOS中手势分为离散型和连续型。一个离散型手势例如tap只发生一次;一个连续的手势例如pinch则在一个时间段内连续发生。对于离散手势,gesture recognizer只向他的target发送一个action消息,而连续型的则会持续的向target发送action消息知道手势结束。

如何定义手势识别交互

在定义自己的手势之前需要下来了解一下手势识别的原理。
手势识别的原理其实就是一个状态机,其原理图如下所示:
参考资料:https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/GestureRecognizer_basics/GestureRecognizer_basics.html#//apple_ref/doc/uid/TP40009541-CH2-SW2






你可能感兴趣的:(IOS手势处理)