【问题标题】:NSString to NSAttributable String with multiple links具有多个链接的 NSString 到 NSAttributable String
【发布时间】:2016-01-14 01:19:20
【问题描述】:

我有以下 NSString:

NSString *example = @" I like cheese and ham and eggs, but ham more than cheese and cheese more than ham!";

我想将其更改为 NSAttributable 字符串,以便我可以在 UITextView 中将其输出,其中 cheese 成为 www.cheese.com 的超链接,ham 成为 www.ham.com 的超链接

这可能吗?

马特

【问题讨论】:

  • 为什么有这么多相关问题?
  • @MaxPoshusta 这个问题离这个问题还差得远。
  • 如果您使用UITextView,因为您认为这是唯一的方法,我想我应该提到可以使用UILabel 来做到这一点。

标签: ios objective-c hyperlink nsstring


【解决方案1】:

使用以下代码。我刚刚手动计算了字符串的范围。但是你可以让它自动化。它只是一个例子。

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"I like cheese and ham and eggs, but ham more than cheese and cheese more than ham!"];
[str addAttribute:NSLinkAttributeName value:[NSURL URLWithString: @"http://www.cheese.com"] range: NSMakeRange(6, [@"cheese" length])];
tempTextView.attributedText = str;

然后使用下面的委托方法来获取操作:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)url inRange:(NSRange)characterRange

【讨论】:

    猜你喜欢
    • 2011-03-17
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 2015-05-17
    • 2016-06-01
    • 2022-11-24
    相关资源
    最近更新 更多