在 UILabel 中插入超链接

Insert a hyperlink in UILabel

我收到来自 api 的文本形式的响应 我想扫描该文本中的单词 "Planned Parenthood health center" 并在该单词上插入一个 hyperlink重定向到 plannedparenthood。org/health-center 门户。

我的做法:

NSString *text = response.content;
text = [text stringByReplacingOccurrencesOfString:@"Planned Parenthood health center" 
                                       withString:@"<a href=\"http://www.plannedparenthood.org/health-center\">Planned Parenthood health center</a>"];

尽管文本中的 link 已被替换。它正在被

取代
<a href=\"http://www.plannedparenthood.org/health-center\">Planned Parenthood health center </a>

怎么了,为什么我在那里没有收到任何 link?我做错了什么我还将用户启用的交互设置为是

老实说,

iOS 并没有很好地处理这个问题,可能是因为它打算让您使用更容易被用户点击的 UIButton。

不过,要完成您想要的,您不能使用 UILabel - 您需要使用 UITextView 并设置其 attributedText 属性:

NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:@"Planned Parenthood health center"];
[attributedString addAttribute: NSLinkAttributeName value: @"http://www.plannedparenthood.com" range: NSMakeRange(0, str.length)];
textView.attributedText = attributedString;

请注意,UITextView 必须可选择但不可编辑。

如果您的属性字符串中有其他未链接的文本,则此方法有一些缺点。例如,如果您有 "Please select here in order to go to Planned Parenthood's website",其中 "here" 是您想要链接的唯一文本部分。在这种情况下,如果您点击文本中单词 "here" 旁边的任何其他位置,您会注意到它可以被用户选中并以蓝色高亮显示。

如果不需要使用 UITextView,那么您将需要使用一些自定义的东西,例如 TTTAttributedLabel