我在向 UILabel 文本添加多种颜色时使用了以下扩展名。结果在 iOS 13 及更高版本中按预期显示,虽然知道它会在 iOS 12.4 中导致问题,因为无论任何更改都显示默认 UILabel 文本颜色。
我最初也在使用属性初始化 ViewDidLoad() 中的 NSMutableAttributedString。想知道是什么原因导致它无法在较旧的 iOS 版本中运行。
extension NSMutableAttributedString {
func setColorForText(textForAttribute: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)
self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
func setColorAndFontForText(textForAttribute: String, withColor color: UIColor, withFont font: UIFont) {
let range: NSRange = self.mutableString.range(of: textForAttribute, options: .caseInsensitive)
self.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
self.addAttribute(NSAttributedString.Key.font, value: font, range: range)
}
}