如何使 NSAttributedString 的特定片段成为 Swift 中的特定颜色

How to make a specific fragment of an NSAttributedString a specific color in Swift

我有一个 UILabel 和一个 NSAttributedString,代码如下:

// just creating from a notification.mainCopy!
var myMutableString = NSMutableAttributedString();
myMutableString = NSMutableAttributedString(string: notification.mainCopy!, attributes: [NSFontAttributeName:UIFont(name: "Helvetica", size: 14.0)!])

// a notification will have a blueMainCopy1 - just a test so no this could be done better
// How to make the blueMainCopy1 blue?
var myItalicizedRangeBlue = (notification.mainCopy! as NSString).rangeOfString(notification.blueMainCopy1!)
let blueFont = UIFont(name: "HelveticaNeue-BoldItalic", size:14.0) // how to make blue
myMutableString.addAttribute(NSFontAttributeName, value: blueFont!, range: myItalicizedRangeBlue)

在这种情况下,如何向 blueFont 添加信息以使其变为蓝色?

有什么方法可以添加:

  let blueAttrs = [NSForegroundColorAttributeName : UIColor.blueColor()]

什么的?

你已经有这个了:

let blueFont = UIFont(name: "HelveticaNeue-BoldItalic", size:14.0)
myMutableString.addAttribute(
    NSFontAttributeName, value: blueFont!, 
    range: myItalicizedRangeBlue)

还有这个:

let blueAttrs = [NSForegroundColorAttributeName : UIColor.blueColor()]

所以现在只需添加另一个属性:

myMutableString.addAttributes(
    blueAttrs, range: myItalicizedRangeBlue) // or any desired range

或者先组合属性再相加,如果范围相同:

let blueFont = UIFont(name: "HelveticaNeue-BoldItalic", size:14.0)
let blueAttrs = [
    NSFontAttributeName : blueFont!,
    NSForegroundColorAttributeName : UIColor.blueColor()
]
myMutableString.addAttributes(
    blueAttrs, range: myItalicizedRangeBlue)