自定义UITableViewCell中UIButton标题字重修改不生效如何解决?
问题解决方案
故障原因
直接修改UIButton的titleLabel.font属性无法持久生效,是因为UIButton会根据自身的状态(普通、高亮、选中)主动管理标题的渲染属性,你直接对titleLabel赋值会被系统内部的配置覆盖。
修复方法
方法1:快速修复(触发重新渲染)
修改完成字体后,重新给按钮设置一遍现有标题,触发UIButton主动重新渲染标题即可生效:
@IBAction func rateButtonPressed(_ sender: UIButton) { guard sender != selectedButton else { return } selectedButton = sender buttons.forEach { button in if button == selectedButton { button.titleLabel?.font = .boldSystemFont(ofSize: 16) } else { button.titleLabel?.font = .systemFont(ofSize: 12) } // 统一触发重新渲染 button.setTitle(button.title(for: .normal), for: .normal) } }
方法2:稳定方案(富文本设置)
如果后续还有其他文本样式修改需求,更稳妥的方式是直接给按钮设置指定状态的富文本,完全自定义样式不会被系统覆盖:
@IBAction func rateButtonPressed(_ sender: UIButton) { guard sender != selectedButton else { return } selectedButton = sender buttons.forEach { button in let title = button.title(for: .normal) ?? "" let font = button == selectedButton ? UIFont.boldSystemFont(ofSize: 16) : .systemFont(ofSize: 12) let attrStr = NSAttributedString(string: title, attributes: [.font: font]) button.setAttributedTitle(attrStr, for: .normal) } }
额外优化点
- 你当前
selectedButton的初始值是一个无意义的空UIButton实例,建议修改为可选类型var selectedButton: UIButton?,初始赋值为nil,避免判断逻辑出错 - 如果cell存在复用场景,建议重写
prepareForReuse方法重置按钮的选中状态和样式,避免复用时展示异常
内容的提问来源于stack exchange,提问作者Amr
相关产品推荐
相关产品推荐

