如何使一个view兼容点击和长按手势 如何高效的响应各自手势的行为?我自己做了一些尝试,且发现了一些高性能的代码实现,希望能和你分享
关于一个item 需要响应点击和长安手势,我这里做了个尝试
第一种是中规中矩的,按苹果文档来了 :
item是一个View
我做如下处理:
[selfaddTapGestureOn];
[selfaddLongPressGesture];
//用苹果的方法来互斥手势
[_longPressGesture requireGestureRecognizerToFail: _tapGesture];
//添加点击手势
-(void)addTapGestureOn
{
if (!_tapGesture) {
_tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
if (![_tapGesture respondsToSelector:@selector(locationInView:)]) {
[_tapGesture release];
_tapGesture =nil;
}else {
_tapGesture.numberOfTapsRequired =1; // The default value is 1.
_tapGesture.numberOfTouchesRequired =1; // The default value is 1.
[self addGestureRecognizer:_tapGesture];
}
}
}
//添加长按手势
- (void)addLongPressGesture
{
if (!_longPressGesture) {
_longPressGesture = [[UILongPressGestureRecognizeralloc] initWithTarget:selfaction:@selector(handleLongPressGesture:)];
if (![_longPressGesturerespondsToSelector:@selector(locationInView:)]) {
[_longPressGesturerelease];
_longPressGesture =nil;
}else {
//_longPressGesture.numberOfTapsRequired = 0; // The default number of taps is 0.
_longPressGesture.minimumPressDuration =0.1f; // The default duration is is 0.5 seconds.
_longPressGesture.numberOfTouchesRequired =1; // The default number of fingers is 1.
_longPressGesture.allowableMovement =10; // The default distance is 10 pixels.
[selfaddGestureRecognizer:_longPressGesture];
}
}
}
第一种方式item继承于view;
直接添加系统的长安手势,然后添加touchend的回调来做点击的响应,结果响应飞快,且精准!
[selfaddLongPressGesture];//处理长按事件
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event//处理点击事件
第二种方式 item继承于button;直接给自己添加点击响应,然后添加长安手势,效果依然杠杠的!
[selfaddTarget:selfaction:@selector(handleTapGesture:)forControlEvents:UIControlEventTouchUpInside];//处理点击
[self addLongPressGesture];//处理长按事件
我都在纳闷这到底为什么尼 可能正规军的处理太复杂了? 希望大家共同的进步,寻找一些更加高效的方式来优化性能。
原文地址:http://blog.csdn.net/zxc110110/article/details/43731333