Hyperlinks in a UITextView

Use NSAttributedString

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Google" 
                                                                       attributes:@{ NSLinkAttributeName: [NSURL URLWithString:@"http://www.google.com"] }];
self.textView.attributedText = attributedString;

Sure, you can set just a portion of the text to be the link. Please read more about the NSAttributedString here.

If you want to have more control and do something before opening the link. You can set the delegate to the UITextView.

- (void)viewDidLoad {
    ...
    self.textView.delegate = self; // self must conform to UITextViewDelegate protocol
}

...

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    // Do whatever you want here
    NSLog(@"%@", URL); // URL is an instance of NSURL of the tapped link
    return YES; // Return NO if you don't want iOS to open the link
}

Leave a Comment