如何将特定属性添加到 Swift 中的 NSAttributedString

how to add specific attributes to a NSAttributedString in Swift

这是一个简单的问题,但在几个地方都出错了,所以我认为有些东西我没有得到(而且它是一个不再在这里的同事应用程序)。我正在将一个 Objective-C 应用程序迁移到 Swift,但我遇到了 NSAttributedString 的一些问题。

有一个 note.body 被设置为 NSMutableAttributedString 并且每个音符都有一个 .frags 字符串数组,这是我们要添加属性的部分。

我有:

var attrs = [NSFontAttributeName : UIFont.systemFontOfSize(9.0)]
var gString = NSMutableAttributedString(string:note.body, attributes:attrs)  // say note.body="birds and bees"

let firstAttributes = [NSForegroundColorAttributeName: UIColor.blueColor(), NSBackgroundColorAttributeName: UIColor.yellowColor(), NSUnderlineStyleAttributeName: 1]
for (val) in note.frags {  // say note.frags=["bees"]
  let tmpVal = val
  gString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: gString.string.rangeOfString(tmpVal))
}

如何添加第一个属性?

我得到的错误是:

Cannot invoke 'addAttribute' with an argument list of type '(String, value: Int, range: Range?)'

问题是您在调用方法时使用了 Range? 参数,而预期的是 NSRange

为确保获得 NSRange,您需要先将 String 转换为 NSString

此代码适用于 Playground:

for val in note.frags {  // say note.frags=["bees"]
    let range: NSRange = NSString(string: gString.string).rangeOfString(val)
    gString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleDouble.rawValue, range: range)
}