美文网首页IOS开发者学习笔记
解决textView:shouldInteractWithURL

解决textView:shouldInteractWithURL

作者: 益达哥哥 | 来源:发表于2018-01-29 11:24 被阅读57次

    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

    相关文章

      网友评论

      • 我想做女人:没用啊 你写的代码 CGPoint tapLocation = [gesture RecognizerlocationInView:textView]; 这 gesture 是什么

      本文标题:解决textView:shouldInteractWithURL

      本文链接:https://www.haomeiwen.com/subject/ekhxzxtx.html