为ios NSString中的某些文本添加点击事件

2024-03-06

我有以下代码,想要使部分文本可单击并调用另一个 UIViewController (不是网站)。

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"testing it out @clickhere"];
NSInteger length = str.length;
[str addAttribute:NSForegroundColorAttributeName value:[UIColor bestTextColor] range:NSMakeRange(0,length)];

NSMutableAttributedString 设置为 UILabel,如下所示:

label.attributedText = str;

最好的方法是什么?我似乎找不到一个很好的答案。

我想要的一个例子是假设我有一个像这样的 UILabel ,其中包含以下文本:

This is my label.  Click here to go to UIViewController1 and then go to UIViewController1 by this #tag.

我希望将文本“此处”传递给第一次单击事件,并将单词“#tag”传递给同一单击事件。


如果您使用 value 字段传入目的地怎么办?

[attributedString addAttribute:NSLinkAttributeName
                         value:[@"destinationController1" stringByAppendingString:username]
                         range:range];

然后重写委托方法:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    if ([URL.scheme isEqualToString:@"destinationController1"]) {
        // Launch View controller
        return NO;
    }
    return YES;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为ios NSString中的某些文本添加点击事件 的相关文章

随机推荐