4

I have a paragraph which is a textView. I want to put hyperlinks inside some of the words in the 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 good enough. When simple taped it doesn't recognise the textView tap. The link must be long pressed to make it work which isn't user friendly.

Is there a work around for this?

  • This solution also doesn't work since I have another tap gesture.
Community
  • 1
  • 1
Thellimist
  • 3,757
  • 5
  • 31
  • 49

2 Answers2

0

An additional tap gesture solution similar to the one in the link you've provided should work, even if you currently have another tap gesture.

If your textView is at the top of the view hierarchy then an additional gesture recognizer added to the textView should just recognize the tap.

If your existing tap gesture is added to a view which is on top of your textView, you can implement UIGestureRecognizerDelegate's shouldReceiveTouch method and handle a tap on the textView in case you hit it, while denying the gesture from receiving the touch. If that's the case then you might not even 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);
    }
}
Artal
  • 8,933
  • 2
  • 27
  • 30
0

Use this code:

textView.dataDetectorTypes = UIDataDetectorTypeLink;
Ardra Thambi
  • 137
  • 2
  • 9