具有多个链接的文本视图或UI标签

问题描述 投票:0回答:3

我要求iOS应用程序使用TextView或UILabel,显示包含文本和两个链接的文本。如果有人点击文本链接,则必须相应地打开该关联链接。

例如:如果您看到下面的图片,则有两个链接。我可以实现这一点,使文本视图文本归属并修改属性检查器中的文本。

现在我的问题是当用户点击弗吉尼亚海滩或尼亚加拉时如何打开链接。如何识别用户点击的文本部分?

enter image description here

要打开的链接:

https://www.vbgov.com/Pages/default.aspx

https://www.niagarafallsusa.com/

我感谢您的帮助。

ios objective-c xcode uilabel uitextview
3个回答
1
投票

您可以使用NSMutableAttributedString来实现此功能。

我写了一个你可以使用的方法,从你的viewDidLoad调用这个方法

- (void)configureLinks
{
    NSString *fullString = @"Please accept the terms and conditions of virginia beach and Niagara.";
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:fullString];

    // Adding attributes
    [attributedString addAttribute:NSLinkAttributeName value:@"https://www.vbgov.com/Pages/default.aspx" range:[fullString rangeOfString:@"virginia beach"]];
    [attributedString addAttribute:NSLinkAttributeName value:@"https://www.niagarafallsusa.com/" range:[fullString rangeOfString:@"Niagara"]];

    // For underline
    [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:[fullString rangeOfString:@"virginia beach"]];
    [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:[fullString rangeOfString:@"Niagara"]];

    // Setting attributed string to textview
    yourTextViewOrLabel.attributedText = attributedString;
}

0
投票

试试这个..我在@MidhunMP答案中添加了下划线代码。

NSString *stringValue = @"Please accept the terms and conditions of virginia beach and Niagara.";
NSMutableAttributedString *output = [[NSMutableAttributedString alloc] initWithString:stringValue];
[output addAttribute:NSLinkAttributeName value:@"https://www.vbgov.com/Pages/default.aspx" range:[stringValue rangeOfString:@"virginia beach"]];
[output addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:[stringValue rangeOfString:@"virginia beach"]];
[output addAttribute:NSLinkAttributeName value:@"https://www.niagarafallsusa.com/" range:[stringValue rangeOfString:@"Niagara"]];
[output addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:[stringValue rangeOfString:@"Niagara"]];
yourTextView.attributedText = output;

0
投票

你可以简单易用地使用KI Label

© www.soinside.com 2019 - 2024. All rights reserved.