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

时间:2015-05-13 01:21:50

标签: swift uikit uilabel

我有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()]

还是什么?

THX

1 个答案:

答案 0 :(得分:3)

你已经有了这个:

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)