我知道这个问题很老,但为了让未来的搜索者保持最新,我想我会添加另一个从 iOS 7 到 10 对我有用的解决方案。它基本上汇集了这里和这里讨论的解决方案,但对它们进行了调整以获得UITextView
识别自定义双击。
它通过子类化UITextView
并覆盖该addGestureRecognizer:
方法来实现这一点,以便将我们的自定义回调注入双击手势并配置单击手势以尊重新的双击钩子。
我这样做是addGestureRecognizer:
因为 aUITextView
会根据其当前状态不断删除和添加手势,因此您必须不断将其重置。
这段代码应该足以让某人开始:
@interface MyCustomTextView ()
/**
* we want to keep track of the current single-tap gesture so we can make sure
* it waits for a double-tap gesture to fail before firing
*/
@property (weak, nonatomic) UITapGestureRecognizer *singleTap;
/**
* we want to keep track of the current double-tap gesture so we can tell a single
* tap gesture to ignore this double-tap when the single tap gesture changes
*/
@property (weak, nonatomic) UITapGestureRecognizer *doubleTap;
@end
@implementation MyCustomTextView
/**
* this will fire when the text view is double-tapped
*
* @param tgr
*/
- (void)_handleTwoTaps:(UITapGestureRecognizer *)tgr
{
// ADD CODE HERE
}
/**
* the reason why I've overridden this methods is these gestures change quite a bit
* depending on the state of the UITextView, (eg, when in focus and out of focus)
* and so this provides a reliable way to make sure any new gestures get updated
* with custom overrides.
*
* @param gestureRecognizer
*/
- (void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
[super addGestureRecognizer:gestureRecognizer];
if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
UITapGestureRecognizer *tgr = (UITapGestureRecognizer *)gestureRecognizer;
if ([tgr numberOfTapsRequired] == 1 && [tgr numberOfTouchesRequired] == 1) {
self.singleTap = tgr;
if (self.doubleTap) {
[tgr requireGestureRecognizerToFail:self.doubleTap];
}
} else if ([tgr numberOfTapsRequired] == 2 && [tgr numberOfTouchesRequired] == 1) {
[tgr addTarget:self action:@selector(_handleTwoTaps:)];
self.doubleTap = tgr;
if (self.singleTap) {
[self.singleTap requireGestureRecognizerToFail:tgr];
}
}
}
}
// NOTE: I'm not sure if this is needed but it's been there for years
// and so I thought I would include it just in case
- (void)removeGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
{
if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
UITapGestureRecognizer *tgr = (UITapGestureRecognizer *)gestureRecognizer;
if ([tgr numberOfTapsRequired] == 2 && [tgr numberOfTouchesRequired] == 1) {
[tgr removeTarget:self action:@selector(_handleTwoTaps:)];
}
}
[super removeGestureRecognizer:gestureRecognizer];
}
@end