Kir*_*ino 1 nsattributedstring ios swift
我有一个这样的方便扩展:
extension NSMutableAttributedString {
func append(string: String, attributes: [String: Any]) {
let attributed = NSMutableAttributedString(string: string)
let range = NSRange(location: 0, length: string.utf16.count)
for (attribute, value) in attributes {
attributed.addAttribute(attribute, value: value, range: range)
}
append(attributed)
}
}
Run Code Online (Sandbox Code Playgroud)
我这样在 UILabel 中设置文本样式:
let normalAttributes = [NSForegroundColorAttributeName: darkGray]
let lightAttributes = [NSForegroundColorAttributeName: lightGray]
let text = NSMutableAttributableString()
text.append("Part 1", attributes: normalAttributes)
text.append("Part 2", attributes: lightAttributes)
Run Code Online (Sandbox Code Playgroud)
所有这些都在自定义 UITableViewCell 类中。发生的事情是文本使用 NIB 文件中的基色渲染,而不是根据我的属性字符串使用自定义前景色 - 直到我执行某些导致单元格重用的操作(例如滚动),之后颜色突然正确渲染.
我似乎找不到对象的生命周期有什么问题,也没有其他地方会弄乱这个标签。标签 fwiw 是一个 IBOutlet,所以我不会每次都创建一个新的或任何奇怪的东西。