我试图将几个属性附加到 NSAttributeString 并不断收到以下错误。
func strikeThroughStyle() {
let range = NSMakeRange(0, 1)
// add styles to self
self.attribute(self.string, atIndex: 0, effectiveRange: range)
}
我收到错误:
最佳答案
attribute:atIndex:effectiveRange:
是一个 getter 方法——它不设置/附加/添加属性,它向您报告字符串中特定索引处的属性值是什么。因此, effectiveRange
参数是一个“输出指针”:您传入一个指向 NSRange
的指针,该方法在返回时填充该指针处的数据。在 Swift 中(以及在 NSAttributedString
扩展中),您可以这样称呼它:
var range = NSRange()
let value = self.attribute(self.string, atIndex: 0, effectiveRange: &range)
但是,这不是您想要的。 您似乎想要在字符串上设置一个属性,而不是获取现有属性的值。为此,请使用
NSMutableAttributedString
和 addAttribute:value:range:
方法,或者(尤其是当您将属性应用于整个字符串时) NSAttributedString
的 init(string:attributes:)
构造函数。关于ios - 无法将 NSRange 类型的值转换为预期的参数类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35300617/