How to Make Uitextview Detect Links for Website, Mail and Phone Number

How to make UITextView detect links for website, mail and phone number

If you are using OS3.0

you can do it like the following

textview.editable = NO;
textview.dataDetectorTypes = UIDataDetectorTypeAll;

How to a clickable url / email / phone number on UITextView

Set the data detector types of your UITextView. There are a number of options:

UIDataDetectorTypePhoneNumber

UIDataDetectorTypeLink

UIDataDetectorTypeAddress

UIDataDetectorTypeCalendarEvent

UIDataDetectorTypeNone

UIDataDetectorTypeAll

So, in your case, you'd probably like to do:

self.myTextView.dataDetectorTypes = UIDataDetectorTypeAll;

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
}

UITextView link detection in iOS 7

It seems that in iOS 7 link detection only works if the UITextView is selectable. So making my UITextView not selectable stopped the the link detection from working.

I also tested this in iOS 6 and I can confirm that in iOS 6 the link detection works fine even with the UITextView not being selectable.



Related Topics



Leave a reply



Submit