简体   繁体   中英

Swift 1.2 NSTextStorage removeAttribute with Range<String.Index>

I have a subclass of NSTextStorage and I'm trying to remove the foreground color of a paragraph the following way:

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

self.removeAttribute(NSForegroundColorAttributeName, range: paragraphRange)

However, I get the following error Cannot invoke 'removeAttribute' with an argument list of type '(String, range: (Range<String.Index>))'

Help Please. I think TextKit on Swift is a mess. Some methods receive/return NSRange but String works with Range<String.Index> making it a hell to work with.

The problem here is that the NSString returned by self.string is automatically bridged to a Swift String . A possible solution is to convert it back to NSString explicitly:

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

Note also that the range operator .. has been replaced by ..< in newer Swift versions (to avoid confusion with ... and to emphasize that the upper bound is not included).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM