将 link 添加到 iOS 中的 nsattributedstrings 时出现越界错误

Out of bound error adding link to nsattributedstrings in iOS

我在 iOS 中使用 objective C 设置了以下代码,但是添加 link 的部分仅适用于从 30 或更小开始的范围。 short_content 的长度应至少为 100 个字。

NSString *short_content = [self getFirstNWords:100 :content];
NSString *link = @" \nClick here to read more   ";
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[short_content stringByAppendingString:link]];

[str addAttribute: NSLinkAttributeName value:@"http://mytest.com/" range:NSMakeRange(str.length - 100, short_content.length)];

如果要设置字符串"link"部分的范围,那么你要:

[str addAttribute: NSLinkAttributeName value:@"http://mytest.com/" range:NSMakeRange(str.length - link.length, link.length)];