自定义 UITableViewCell 中带有属性文本的 UILabel:颜色在重用之前不会呈现(iOS10)

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,所以我不会每次都创建一个新的或任何奇怪的东西。

Kir*_*ino 5

事实证明它与以下问题相同:

在单元格出列并重新加载之前,tableviewcell 中的属性字符串不会显示粗体文本

所以它通过nil在设置attributeText. 烦人,但很容易做到这一点。