Joh*_*Doe 2 nsattributedstring ios swift
我试图将一些属性附加到NSAttributeString并继续得到以下错误.
func strikeThroughStyle() {
let range = NSMakeRange(0, 1)
// add styles to self
self.attribute(self.string, atIndex: 0, effectiveRange: range)
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
无法将'NSRange'(又名'_NSRange')类型的值转换为预期的参数类型'NSRangePointer'(又名'UnsafeMutablePointer <_NSRange>')
attribute:atIndex:effectiveRange:
是一个getter方法 - 它不设置/附加/添加属性,它会向您报告属性值在字符串中的特定索引处的内容.因此,effectiveRange
参数是一个"out-pointer":你传入一个指向a的指针NSRange
,该方法在返回时填充该指针的数据.在Swift(以及NSAttributedString
扩展中)中,您可以这样调用它:
var range = NSRange()
let value = self.attribute(self.string, atIndex: 0, effectiveRange: &range)
Run Code Online (Sandbox Code Playgroud)
但是,这不是你想要的.您似乎想要在字符串上设置属性,而不是获取现有属性的值.为此,使用NSMutableAttributedString
和addAttribute:value:range:
方法,或(特别是如果你将属性应用于整个字符串)NSAttributedString
的init(string:attributes:)
构造函数.