简体   繁体   中英

Tap gesture recognizer interferes with URL taps in UITextView

I have a disabled text view with a tap gesture recognizer attached to it. The problem is that this gesture recognizer intercepts all taps including those made on autodetected URLs (text view has data detectors turned on). Is there any way to prevent it from happening, so when a user taps an URL it's handled by text view itself (opening in Safari) and when a user taps somewhere else then my gesture recognizer is called?

The best way would be if you could access the gesture recognizer used by the data detectors (then specifying that your tap recognizer should have lower priority than that one, by using the delegate's gestureRecognizer:shouldRequireFailureOfGestureRecognizer: etc), but I don't think this is possible (anyone feel free to correct me here if I'm wrong).

Instead, you could try to add a delegate to the text view and check if the textView:shouldInteractWithURL:inRange: was called during the active period of your gesture recognizer (then only run your handler when not handled by the UITextView ).

A bit hacky but it works:

if let recognizers = yourTextView.gestureRecognizers {
    for recognizer in recognizers {
        if recognizer.name == "UITextInteractionNameLinkTap" {
            myCustomTapGestureRecognizer.require(toFail: recognizer)
        }
    }
}

The name of the recognizer for detecting links is "UITextInteractionNameLinkTap"

Please make sure your textview is not a subview of other view. If it is a subview, so add UITextViewDelegate for the top view and then add this one in viewDidLoad :

 - (void)viewDidLoad
{
    [super viewDidLoad];
    yourTextview.delegate = self;
    yourTextview.editable = NO;
    yourTextview.selectable = YES;
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM