Hyperlink / url inside textView

I have a paragraph which is a textView. I want to put hyperlinks inside some words in a paragraph.

enter image description here

var attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSLinkAttributeName, value: hyperlink, range: range)

var linkAttributes = [NSForegroundColorAttributeName: UIColor.blueColor(),
            NSUnderlineStyleAttributeName: 1
        ]

textView!.linkTextAttributes = linkAttributes        
textView!.attributedText = attributedString
textView!.delegate = self

      

UITextViewDelegate

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
    if UIApplication.sharedApplication().canOpenURL(URL) {
        return true
    } else {
        CozyStyles.alert(title: "Sorry", message: (URL.scheme!).capitalizeFirst + " is not installed", action: "OK")
        return false
    }
}

      

This approach works, but it doesn't work well enough. When simply recording to tape, it doesn't recognize tapView. The link has to be long-clicked to make it work, which is not user-friendly.

Is there a job for this?

+3


source to share


2 answers


An additional gesture solution like the one you listed should work even if you currently have another tap gesture.

If your textView is at the top of the view hierarchy, the additional gesture recognition feature added to the textView should simply recognize the click.



If your existing add gesture is added to a view that sits on top of your text element, you can implement the UIGestureRecognizerDelegate's shouldReceiveTouch method and handle the short press on the textView in case you hit it, without denying that the gesture was touched. If in this case you might need an additional gesture:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    CGPoint location = [touch locationInView:self.view];
    if (CGRectContainsPoint(self.textView.frame, location)) {
        [self handleTapOnTextViewAtLocation:[self.view convertPoint:location toView:self.textView]];
        return NO;
    }
    return YES;
}

- (void)handleTapOnTextViewAtLocation:(CGPoint)location {
    UITextPosition *textPosition = [self.textView closestPositionToPoint:location];
    NSDictionary *textStyling = [self.textView textStylingAtPosition:textPosition inDirection:UITextStorageDirectionForward];
    NSURL *url = textStyling[NSLinkAttributeName];
    if (url) {
        NSLog(@"url tapped: %@", url);
    }
}

      

0


source


Use this code:



textView.dataDetectorTypes = UIDataDetectorTypeLink;

      

0


source







All Articles