iOS手势
2013-10-05 13:11
246 查看
iOS手势
在iPhone中,我们除了用touchesBegan、touchesMoved、touchesEnded、touchesCancelled这组方法来控制使用者的手指触控外,也可以用UIGestureRecognizer 的衍生类别来进行判断,该类别的好处是有自己现成的手势,开发者可以自己计算手指移动的轨迹。1、首先看下touchesBegan、touchesMoved、touchesEnded、touchesCancelled者四个方法的使用。
touchesBegan:是用户第一次接触屏幕时响应的方法。
- (void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *)event{
NSUInteger numType = [[touches anyObject] tapCount];
NSUInteger numTouches = [touches count];
}
touchesMoved:是用户手指移过屏幕时响应的方法。这里可以得到当前手指的位置以及原来的位置等信息。
touchesEnded:用户手指离开屏幕时响应的方法。
touchesCancelled:当发生某些事件导致手势中断时响应的方法,要说明的是调用了该方法就不会响应touchesEned方法了。
2、现在了解下UIGestureRecognizer的使用
UIGestureRecognizer衍生类别有:UITapGestureRecognizer、UIPinchGestureRecognizer、UIRotationGestureRecognizer、UISwipeGestureRecognizer、UIPanGEstureRecognizer、UiLongPressGestureRecognizer,他们所代表的手势分别是Tap(点一下)、Pinch(二指往外或往内拨动)、Rotation(旋转)、Swipe(滑动、快速移动)、Pan(拖移、慢速移动)、LongPress(长时间按)。
- (void)viewDidLoad {
UISwipeGestureRecognizer* recognizer;
// handleSwipeFrom 是偵測到手势,所要响应的方法
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleSwipeFrom)];
// 不同的 Recognizer 有不同的实体变数
// 例如 SwipeGesture 可以指定方向
// 而 TapGesture 則可以指定次數
recognizer.direction = UISwipeGestureRecognizerDirectionUp
[self.view addGestureRecognizer:recognizer];
[recognizer release];
}
- (void)handleSwipeFrom:(UISwipeGestureRecognizer*)recognizer {
// 触发手勢事件后,在这里作些事情
// 底下是刪除手势的方法
[self.view removeGestureRecognizer:recognizer];
}
但是这里有个问题,Tap和LongPress,一个是点击一次一个长按,所以当我们点击屏幕的时候,我们怎么分清这是点击还是准备长按呢?Swipe和Pan也有这样的问题,只要手指一移动就会出发Pan,这样的话永远不会出发Swipe,这个问题要出现的前提是同时注册了这些手势。
所以需要一个解决方法:幸好UIGestureRecognizer类提供了一个方法requireGestureRecognizerToFail它可以指定某一个recognizer,即便自己满足条件; 也不会立即执行会等到指定的recognizer确定失败之后才触发。
- (void)viewDidLoad {
// 单击的 Recognizer
UITapGestureRecognizer* singleRecognizer;
singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleSingleTapFrom)];
singleTapRecognizer.numberOfTapsRequired = 1;
// 单击
[self.view addGestureRecognizer:singleRecognizer];
// 双击的 Recognizer
UITapGestureRecognizer* doubleRecognizer;
doubleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:selfaction:@selector(handleDoubleTapFrom)];
doubleTapRecognizer.numberOfTapsRequired = 2;
// 双击
[self.view addGestureRecognizer:doubleRecognizer];
// 关键在这一行,如果双击确定偵測失败才會触发单击
[singleRecognizer requireGestureRecognizerToFail:doubleRecognizer];
[singleRecognizer release];
[doubleRecognizer release];
}
相关文章推荐
- 【分享】iOS下view hierarchy工具
- IOS 判断是否第一次进入 并使用navigationController跳转
- IOS XML解析
- ios创建并发线程
- 碳足迹计算器ios版总结
- iOS开发之Xcode篇
- ios开发-應用程式的設定檔info.plist
- ios 常用字符串的操作
- ios 开发中 developer tools access 总是要输入密码问题的解决
- IOS math.h函数
- ios开发-设置view背景
- ios开发-自定义启动画面Default.png加载时间
- iOS完整学习路线图
- 在 Xcode 4.4 和 iOS 4.3+ 中使用下标语法
- 一个iOS 框架介绍:MKNetworkKit
- iOS 输出color的组成(components)
- 【初学】iOS学习笔记-@property @synthesize oc=_oc
- iOS设计模式之一:MVC模式和单例模式
- IOS开发博客学习
- IOS私有API的了解