想给UITextView添加一个功能,长按呼出新的界面。
恩,开始干吧!
首先先创建一个长按手势。
UILongPressGestureRecognizer *longPress =[[UILongPressGestureRecognizer alloc] initWithTarget:selfaction:@selector(longBangClick:)];
[self.textView addGestureRecognizer:bangPress];
添加后,长按响应,哎呦不错哦!
不对,UITextView获取焦点后,怎么再进行长按只出放大镜了👀!就知道事情没那么简单!
分析一下吧:
在TextView没有获取到焦点时,事件能够响应,获取到焦点后无法响应,因此初步怀疑是GestureRecognizer事件冲突,因此:
for(UIGestureRecognizer *recognizer in self.textView.gestureRecognizers) {
NSLog(@"%@",[recognizer class]);
}
2017-03-24 09:42:10.521927 Medicare[9494:1168221] UIScrollViewDelayedTouchesBeganGestureRecognizer
2017-03-24 09:42:10.522073 Medicare[9494:1168221] UIScrollViewPanGestureRecognizer
2017-03-24 09:42:10.522147 Medicare[9494:1168221] UITextTapRecognizer
2017-03-24 09:42:10.522213 Medicare[9494:1168221] UITapAndAHalfRecognizer
2017-03-24 09:42:10.522271 Medicare[9494:1168221] UITextTapRecognizer
2017-03-24 09:42:10.522405 Medicare[9494:1168221] UIVariableDelayLoupeGesture
什么鬼... 不管,先分析下吧,前两个是ScrollView的事件,下面四个类名都找不到,应该是私有方法,想自定义就无望了。但是根据类名UITextTapRecognizer,UITapAndAHalfRecognizer 判断这两个应该跟属于点击手势。
for(UIGestureRecognizer *recognizerin self.textView.gestureRecognizers)
{
if([NSStringFromClass([recognizer class]) isEqualToString:@"UITextTapRecognizer"] || [NSStringFromClass([recognizer class]) isEqualToString:@"UITapAndAHalfRecognizer"]) {
recognizer.enabled=NO;
}
}
暴力一点总是好的!现在手势已经可以正常使用了,可是TextView焦点获取不到了!但这样可以证实UILongPressGestureRecognizer确实和UITextTapRecognizer,UITapAndAHalfRecognizer有事件冲突,那下面就好解决了!
UILongPressGestureRecognizer *longPress =[[UILongPressGestureRecognizer alloc] initWithTarget:selfaction:@selector(longBangClick:)];
longPress.delegate=self;
[self.textView addGestureRecognizer:bangPress];
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*) otherGestureRecognizer{
NSLog(@"gestureRecognizer%@",[gestureRecognizer class]);
NSLog(@"otherGestureRecognizer%@",[otherGestureRecognizer class]);
returnYES;
}
果不其然
2017-03-24 10:08:14.298371 Medicare[9530:1172527] gestureRecognizer UILongPressGestureRecognizer
2017-03-24 10:08:14.298449 Medicare[9530:1172527] otherGestureRecognizer UITextTapRecognizer
最终
- (BOOL)gestureRecognizer:(UIGestureRecognizer*) gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*) otherGestureRecognizer{
if([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]] && [NSStringFromClass([otherGestureRecognizer class])isEqualToString:@"UITextTapRecognizer"]){
returnNO;
}
returnYES;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
returnNO;
}
最后可以通过上面的方法去除系统UIMenuController的出现。
网友评论