突出显示的文本颜色在选择表视图单元格时更改 UILabel 的文本颜色


有许多

示例可以在选择UITableViewCell时更改UILabel文本的颜色。但是所有示例都用以下几行解释

if cell.selected {
  cell.txtLabel1.textColor = UIColor.redColor()
}else {
  cell.txtLabel1.textColor = UIColor.blackColor()
} 

但是设置 cell.txtLabel1.highlightedTextColor = UIColor.redColor(( 非常简单。粗线会导致任何问题吗,为什么其他示例没有粗体行实现?

如果不将"突出显示"设置为 UILabel,则在选择 UITableViewCell 时也会更改文本的颜色。下面粘贴代码以供参考

class MenuViewCell: UITableViewCell {
    @IBOutlet weak var lblTitle:UILabel?
    @IBOutlet weak var imgIcon:UIImageView?
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        let selectedView = UIView()
        selectedView.backgroundColor = UIColor(colorLiteralRed: 244.0/255.0, green: 244.0/255.0, blue: 245.0/255.0, alpha: 1)
        selectedBackgroundView = selectedView
        lblTitle?.highlightedTextColor = UIColor(colorLiteralRed: 224.0/255.0, green: 121.0/255.0, blue: 43.0/255.0, alpha: 1)
    }
    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
} 

粗线会导致任何问题。

我认为在UILabel上使用此属性没有任何问题,如果您阅读此属性的文档,它会指出:

只要 isT突出显示属性设置为 true,此颜色就会自动应用于标签。

更多信息在这里

这是最有效的问题,但当然用法会有所不同,如下所示:

UILabel.highlightedTextColor = UIColor.red

切换isHighlighted

UILabel.isHighlighted = cell.isSelected

更新

要在设置cell.isSelected时自动更改UILabel.isHighlighted,可以子类UITableViewCell,如下所示:

class MyTableViewCell: UITableViewCell {
    @IBOutlet var label = UILabel!
    override var isSelected: Bool {
        didSet {
            label.isHighlighted = isSelected
        }
    }
}

最新更新