如何在Swift中使用addAttribute

时间:2015-08-26 13:59:23

标签: ios swift

我正在尝试添加指向UITextViews的链接,因此我正在关注this post中的代码。相关的Objective-C代码是

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"];
[attributedString addAttribute:NSLinkAttributeName
                         value:@"username://marcelofabri_"
                         range:[[attributedString string] rangeOfString:@"@marcelofabri_"]];

但是当我在Swift 2中尝试这个时

var attributedString = NSMutableAttributedString(string: "This is an example by @marcelofabri_")
attributedString.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: attributedString.string.rangeOfString("/marcelofabri_"))

我收到错误

  

无法调用' addAttribute'使用类型'的参数列表(字符串,值:字符串,范围:范围?)'

我需要更改什么才能让它发挥作用?

1 个答案:

答案 0 :(得分:31)

尝试使用NSString查找范围而不是Swift String

var attributedString = NSMutableAttributedString(string: "This is an example by @marcelofabri_")
attributedString.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: (attributedString.string as NSString).rangeOfString("/marcelofabri_"))