UIGestureRecognizer是手势的基类,定义了所有手势的基本行为。其它均为它的子类。
UITapGestureRecognizer
UIPinchGestureRecognizer
UIRotationGestureRecognizer
UISwipeGestureRecognizer
UIPanGestureRecognizer
UILongPressGestureRecognizer
都继承自UIGestureRecognizer,它们都具有相同的基本行为,但在具体上又有所不同。
以下是这些手势的代码实现:
1.先对各个手势进行创建以及一些参数的设定:
//--------单击,双击-----------
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[self.view addGestureRecognizer:singleTap];
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
doubleTap.numberOfTapsRequired = 2;//默认为1
[self.view addGestureRecognizer:doubleTap];
[singleTap requireGestureRecognizerToFail:doubleTap];
//--------轻扫------------
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)];
swipeGesture.direction = UISwipeGestureRecognizerDirectionUp;
[self.view addGestureRecognizer:swipeGesture];//默认向右
//--------滑动------------
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[self.view addGestureRecognizer:panGesture];
//--------长按------------
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
longPress.minimumPressDuration = 3;//默认为0.5
[self.view addGestureRecognizer:longPress];
//--------旋转------------
UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotation:)];
[self.view addGestureRecognizer:rotationGesture];
2.各个手势触发时调用的相应方法:
-(void)tap:(UITapGestureRecognizer *) tap
{
if (tap.numberOfTapsRequired==1)
{
NSLog(@”单击”);
}else if (tap.numberOfTapsRequired==2)
{
NSLog(@”双击”);
}else//不能识别多击
{
NSLog(@”多击”);
}
}
-(void)swipe:(UISwipeGestureRecognizer *) swipeGesture
{
NSLog(@”轻扫”);
}
-(void)pan:(UIPanGestureRecognizer *)panGesture
{
CGPoint point = [panGesture locationInView:self.view];
NSLog(@”%@”,NSStringFromCGPoint(point));
}
-(void)longPress:(UILongPressGestureRecognizer *)longPressGesture
{
NSLog(@”%u”,[longPressGesture state]);
}
-(void)rotation:(UIRotationGestureRecognizer *)rotation
{
float depress = rotation.rotation*(180/(M_PI));
NSLog(@”%f”,depress);
}
总结:iOS中各个手势其实是由事件构成,而基本事件都具有相应的处理方法,例如开始触摸,正在移动,手指离开屏幕时都会调用相应的方法,而手势正是将这些相应的处理方法进行了集合。