iphone - UILabel - 作为文本和链接的字符串

标签 iphone ios nsstring uilabel

我有一个 UILabel,我从服务器获取其文本。一些文本将被识别为链接,并且在触摸这些链接时应该执行一些操作。例如

NSString *str = @"我的电话号码是645-345-2345 我的地址是xyz ";

这是 UILabel 的完整文本。我只有一个 UILabel 用于显示此文本(文本是动态的。我只是举了一个例子。)。单击这些链接后,我需要执行一些操作,例如导航到某个不同的屏幕或调用电话。
我知道我可以在 OHAttributedLabel 的帮助下显示此类文本。链接可以显示如下:

[label1 addCustomLink:[NSURL URLWithString:@"http://www.foodreporter.net"] inRange:[txt rangeOfString:someString]];  

但我想知道如何让这些文本链接执行某些操作,例如导航到不同的屏幕或调用电话。
如果需要更多解释,请告诉我。

最佳答案

您可以将自定义操作添加到任何可用的 UILabel 替换,这些替换支持使用稍后将拦截的 URL 方案 的链接:

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];

然后,在您的 TTTAtributedLabelDelegate 中:

- (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 的一个分支。

如果您想要更复杂的方法,请查看 Nimbus Attributed Label .它支持开箱即用的自定义链接。

关于iphone - UILabel - 作为文本和链接的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8839464/

相关文章:

iphone - 右对齐 EntryElement

ios UI 对于我的 Storyboard来说不可扩展

ios - UISaveVideoAtPathToSavedPhotosAlbum 输出

ios - MYSQL 和 Swift - 上传图像和文件 ||使用 Alamofire 会更好吗?

ios - UIPopOverController 的推送操作

ios - libxslt:编译错误

ios - 如何在 NSString 中获取 NSArray 对象并将该对象一一发送?

ios - 如何检测一个 NSString 是否包含一个大写字母

ios - stringWithFormat和initWithFormat在ARC中导致不同的值

ios - 不透明的 UIView 不允许我在它后面滚动 UIView