问题描述
我有一个 UILabel
,我从服务器获取其文本.一些文本将被标识为链接,并且在触摸这些链接时应该执行一些操作.例如
I have a UILabel
whose text I am getting from a server. Some of the text is to be identified as links, and on touching those links some action should be performed. e.g.
NSString *str = @"我的电话号码是 645-345-2345 而我的地址是 xyz";
NSString *str = @"My phone number is 645-345-2345 and my address is xyz";
这是UILabel
的完整文本.我只有一个 UILabel
用于显示此文本(文本是动态的.我只是举了一个例子.).单击这些链接时,我需要执行一些操作,例如导航到某个不同的屏幕或拨打电话.
我知道我可以在 OHAttributedLabel 的帮助下显示这样的文本.链接可以显示如下:
This is the complete text for UILabel
. I have only one UILabel
for displaying this text (Text is dynamic. I just gave an example.). On clicking these links I need to perform actions like navigating to some different screen or make a call.
I know that I can display such text with help of OHAttributedLabel. And the links can be displayed as follows :
[label1 addCustomLink:[NSURL URLWithString:@"http://www.foodreporter.net"] inRange:[txt rangeOfString:someString]];
但我想知道如何让这些文本链接执行某些操作,例如导航到不同屏幕或拨打电话.
如果需要更多解释,请告诉我.
But I wonder how can I make these text links perform some action like navigation to different screen or making a call.
Let me know if more explanation is required.
推荐答案
您可以向任何可用的 UILabel
替换添加自定义操作,这些替换支持使用 fake 的链接网址方案:
You can add custom actions to any of the available UILabel
replacements that support links using a fake URL scheme that you'll intercept later:
TTTAttributedLabel *tttLabel = <# create the label here #>;
NSString *labelText = @"Lost? Learn more.";
tttLabel.text = labelText;
NSRange r = [labelText rangeOfString:@"Learn more"];
[tttLabel addLinkToURL:[NSURL URLWithString:@"action://show-help"] withRange:r];
然后,在您的 TTTAttributedLabelDelegate
中:
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
if ([[url scheme] hasPrefix:@"action"]) {
if ([[url host] hasPrefix:@"show-help"]) {
/* load help screen */
} else if ([[url host] hasPrefix:@"show-settings"]) {
/* load settings screen */
}
} else {
/* deal with http links here */
}
}
TTTAttributedLabel 是 OHAttributedLabel 的一个分支.
TTTAttributedLabel is a fork of OHAttributedLabel.
如果您想要更复杂的方法,请查看Nimbus 属性标签.它支持开箱即用的自定义链接.
If you want a more complex approach, have a look to Nimbus Attributed Label. It support custom links out-of-the-box.
这篇关于UILabel - 作为文本和链接的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!