添加到NSString iOS的超链接

use*_*810 1 objective-c hyperlink nsstring

我有一个简单的NSString,例如:

NSString*text = @"Stackoverflow太神奇了!"

我想把Stackoverflow这个词变成指向https://stackoverflow.com/的超链接,并且仍然可以将字符串作为变量输出.这可能吗?

Dai*_*jan 7

一个字符串只包含字母 - 没有格式化的东西.

要使一个部分成为一个链接,你必须使用属性文本并使用url为NSLink属性分配第一个单词:

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];
Run Code Online (Sandbox Code Playgroud)

在文本视图中显示它,UILabel不支持单击AFAIK