user1419810
user1419810

Reputation: 846

Add hyperlinks to NSString iOS

I have a simple NSString, for example :

NSString *text = @"Stackoverflow is amazing!"

and I'd like to turn the word Stackoverflow into a hyperlink pointing to https://stackoverflow.com/ and still be able to output the string as a variable. Is this possible?

Upvotes: 1

Views: 3883

Answers (1)

Daij-Djan
Daij-Djan

Reputation: 50089

A string only contains letters - no formatting what so ever.

To make a part into a link, you have to Attributed Text and assign the first word a NSLink attribute with the url:

NSURL *url = [NSURL URLWithString:@"http://www.google.de"];

NSAttributedString *my = [NSAttributedString attributedStringWithString:@"my"
                                                             attributes:@{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont systemFontWithSize:16]}];
NSAttributedString *link = [NSAttributedString attributedStringWithString:@"Link"
                                                               attributes:@{NSForegroundColorAttributeName:[UIColor blue], NSFontAttributeName:[UIFont systemFontWithSize:16], NSLinkAttributeName:url}];
NSMutableAttributedString *attr = [my mutableCopy];
[attr appendAttributedString:link];

show it in a textview, a UILabel doesn't support clicking AFAIK

Upvotes: 7

Related Questions