gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:22:53 25 4
gpt4 key购买 nike

我有一个 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)

关于swift - 如何在 Swift 中使 NSAttributedString 的特定片段成为特定颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com