UILabel - 作为文本和链接的字符串 [英] UILabel - string as text and links

查看:106
本文介绍了UILabel - 作为文本和链接的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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 替换项,这些替换项支持使用虚假 URL方案的链接ll后来拦截:

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 - 作为文本和链接的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆