当用户用两根手指触摸屏幕时,我需要应用一个功能。
我的问题就是屏幕有一个UITextView
。
屏幕上还有活动键盘,这就是通常的方法(UITapGestureRecognizer
)不能用于此配置的原因。
我该怎么做?
感谢。
答案 0 :(得分:3)
您需要向UITapGestureRecognizer
添加UITextView
。
以下是你必须做的事情:
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(respondToTap)];
[singleTap setNumberOfTapsRequired:2];
[self.yourTextView addGestureRecognizer:tapRecognizer];
-(void)respondToTap{
//do whatever you have to when textfield is double tapped
}
答案 1 :(得分:1)
由于您无法将UIKeyboard
子类化为传递触摸,因此此链接可以为您提供帮助。
Detect if the user has touched the screen
有一个UIWindow
的子类 - 如果你将它设置为主应用程序窗口(在appDelegate中),你可能会在它们到达键盘之前触及它们。在那里,您应该能够检查触摸是否在UITextField
区域(并正确处理)或将它们发送到响应链。
不像使用手势识别器那样优雅,但你可以使它工作。
答案 2 :(得分:0)
与this answer I gave to a similar question类似,但有一点需要注意,我只在iOS 10上使用此功能,您可以通过使用自定义类扩展UITextView
并覆盖addGestureRecognizer:
来实现此目的
跟踪singleTap只是作为添加两个手指点击的标记,因为UITextView
不断添加和删除手势:
@interface MyCustomTextView ()
@property (weak, nonatomic) UITapGestureRecognizer *singleTap;
@end
@implementation MyCustomTextView
/**
* this will fire when the text view is tapped with two fingers
*
* @param tgr
*/
- (void)_handleTwoTouches:(UITapGestureRecognizer *)tgr
{
// ADD CODE HERE
}
- (void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
[super addGestureRecognizer:gestureRecognizer];
if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
UITapGestureRecognizer *tgr = (UITapGestureRecognizer *)gestureRecognizer;
if ([tgr numberOfTapsRequired] == 1 && [tgr numberOfTouchesRequired] == 1) {
if (!self.singleTap) {
self.singleTap = tgr;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_handleTwoTouches:)];
tap.numberOfTapsRequired = 1;
tap.numberOfTouchesRequired = 2;
[super addGestureRecognizer:tap];
}
}
}
}
@end