我有这样的便利扩展:
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)
}
}
我正在我的UILabel中设置文本样式:
let normalAttributes = [NSForegroundColorAttributeName: darkGray]
let lightAttributes = [NSForegroundColorAttributeName: lightGray]
let text = NSMutableAttributableString()
text.append("Part 1", attributes: normalAttributes)
text.append("Part 2", attributes: lightAttributes)
所有这些都在一个自定义的UITableViewCell类中 . 发生的事情是文本使用NIB文件中的基色进行渲染,而不是根据我的属性字符串自定义前景颜色 - 直到我做某事(如滚动)导致单元格重用,之后突然颜色正确呈现 .
我似乎无法发现对象的生命周期有任何问题,而且没有其他地方可以搞乱这个标签 . 标签fwiw是一个IBOutlet,所以我不是每次创建一个新的或任何奇怪的东西 .
2 回答
原来它是同样的问题:
Attributed string in tableviewcell not showing bold text until the cell is dequeued and reloaded
因此,在设置
attributeText
之前,通过在标签上将字体和颜色设置为nil
来解决此问题 . 烦人,但很容易做到这一点 .正如@Kiril Savino建议的那样 . 将
UILabel
的UILabel
设置为nil
可以轻松解决问题 .但是我今天注意到的另一件事是
Default Font
来自Storyboard or XIB
.它应该是
System Font
来自Storyboard or XIB
来使这项工作 . 如果您使用了其他Custom Font
,则无法使用 .所以,确保
UILabel
的Default Font
应为System Font
.谢谢 .