Swift 1.2 NSTextStorage removeAttribute with Range <string.index> </string.index>

时间:2015-04-12 05:32:39

标签: ios swift textkit

我有一个NSTextStorage的子类,我试图通过以下方式删除段落的前景色:

var paragraphRange = self.string.paragraphRangeForRange(
        advance(self.string.startIndex, theRange.location)..advance(self.string.startIndex, theRange.location + theRange.length))

self.removeAttribute(NSForegroundColorAttributeName, range: paragraphRange)

但是,我收到以下错误Cannot invoke 'removeAttribute' with an argument list of type '(String, range: (Range<String.Index>))'

请帮助。我认为Swift上的 TextKit 是一团糟。有些方法接收/返回NSRange但是String与Range<String.Index>一起使用,这使得它成为一个可以使用的地狱。

1 个答案:

答案 0 :(得分:3)

此处的问题是NSString返回的self.string 自动桥接到Swift String。可能的解决方案是 将其明确地转换回NSString

func removeColorForRange(theRange : NSRange) {
    let paragraphRange = (self.string as NSString).paragraphRangeForRange(theRange)
    self.removeAttribute(NSForegroundColorAttributeName, range: paragraphRange)
}

另请注意,范围运算符..已被..<替换 在较新的Swift版本中(以避免与...混淆 强调不包括上限。