Creating Clickable Hyperlinks from a URL, Phone Number or Address

The following tips shows a quick way to create clickable hyperlinks using a UITextView. The trick is to set the dataDetectorTypes property to specify the data type you are after, from there, upon a tap the link will launch the appropriate application, namely Safari, Phone Dialer or Maps.


Clickable URL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Create textview, centering horizontally
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 10, 320, 50)];
 
// Set font, background and alignment
[textView setFont:[UIFont boldSystemFontOfSize:16]];
[textView setBackgroundColor:[UIColor blackColor]];
[textView setTextAlignment:UITextAlignmentCenter];
 
// Unfortunately the link will show as blue even with this setting
//  [textView setTextColor:[UIColor greenColor]];
 
// Edit and scrolling off  
[textView setEditable:NO];
[textView setScrollEnabled:NO];
 
// Set data type to specify URL/link
[textView setDataDetectorTypes:UIDataDetectorTypeLink];
 
// Set text as URL
[textView setText:@"iOSDeveloperTips.com"];  
 
[self.view addSubview:textView];
Clickable Phone Number

To change up the code to support a clickable phone number, replace lines 16-21 with the following:

// Set data type to phone number
[textView setDataDetectorTypes:UIDataDetectorTypePhoneNumber];
 
// Set text as phone number
[textView setText:@"800-555-1212"];
Clickable Address

With the release of iOS 4.0, you can now create a clickable address. Tapping on the link will launch the Maps application.

// Set data type to address
[textView setDataDetectorTypes:UIDataDetectorTypeAddress];
 
// Set text as phone number
[textView setText:@"1 Infinite Loop, Cupertino, CA 95014"];
  1. Let’s say that you want to bring up the address in an MKMapView instead of exiting the app; is there a quick and easy way to intercept the action? (I already do this in one published application — pull up a map inside the app using a selected address — but not with the UITextView method you describe above.)

    By analogy, I’m thinking of how you can override – (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType to, for example, insert a default subject line into a “mailto” url.

  2. can i have text “Custom Link “in place of iOSDeveloperTips.com but still make it hyperlink

    • As the example is written, the URL is recognized (by the OS) and a clickable link is created. If you work with Javascript and embed into a webview, you can create clickable text with a separate URL.

Comments are closed.