解决textView:shouldInteractWithURL:inRange:不能tap事件触发的问题

textViewDelegate代理里面有个url点击跳转的回调,- (BOOL)textView:(UITextView*)textView shouldInteractWithURL:(NSURL*)URL inRange:(NSRange)characterRange;我们在UITextView里面做一些超链接特别好用。但是在8/9系统上要触发这个回调是需要一种特殊的手势-->点击并按住,普通的tap事件根本触发不了它,那么怎么解决呢?

Add your tap recognizer:

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addGestureRecognizer:)];

[myTextView  addGestureRecognizer:tapRecognizer];

实现对应的方法即可:

- (void)addGestureRecognizer:(UIGestureRecognizer*)gestureRecognizer

{

    if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]])

    {

        UITextView* textView = (UITextView*)gestureRecognizer.view;

        CGPoint tapLocation = [gesture RecognizerlocationInView:textView];

        UITextPosition*textPosition = [textView closestPositionToPoint:tapLocation];

        NSDictionary *attributes = [textView textStylingAtPosition:textPosition inDirection:UITextStorageDirectionForward];

        NSURL*url = attributes[NSLinkAttributeName];

        if(url) {

            NSRangerange =  [self.text rangeOfString:@“xxx”];

            if([self.delegateconformsToProtocol:@protocol(UITextViewDelegate)] && [self.delegaterespondsToSelector:@selector(textView:shouldInteractWithURL:inRange:)]) {

                [self.delegate textView:self shouldInteractWithURL:url inRange:range];

            }

        }

    }

    [super addGestureRecognizer:gestureRecognizer];

}

参考:https://stackoverflow.com/questions/22379595/uitextview-link-tap-recognition-is-delayed

你可能感兴趣的:(解决textView:shouldInteractWithURL:inRange:不能tap事件触发的问题)