如何在 Swift 中使用 addAttribute

Posted

技术标签:

【中文标题】如何在 Swift 中使用 addAttribute【英文标题】:How to use addAttribute in Swift 【发布时间】:2015-08-26 13:59:22 【问题描述】:

我正在尝试添加指向 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】:

尝试使用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_"))

【讨论】:

问题是我使用的是NSAttributedString 而不是NSMutableAttributedString【参考方案2】:

您根据需要使用 Range 而不是 NSRange。看看:

NSRange from Swift Range?

【讨论】:

以上是关于如何在 Swift 中使用 addAttribute的主要内容,如果未能解决你的问题,请参考以下文章

“NSAttributedString”类型的值没有成员“addAttributes”

swift UIButton中文本添加下划线的方法

使用 Swift 在 iOS 11 中为 NSAttributedString 添加删除线

model.addAttribute() 对于每个循环

Swift 属性标题语法

SimpleXMLElement 在 addChild 和 addAttribute 中处理文本值的基本原理