[英]How to change color of the text in visible cell of tableview in ios swift
[英]Change text color in tableview cell in didHighlightRowAt
我有以下代码:
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell!.contentView.backgroundColor = .blue
cell?.textLabel?.textColor = UIColor.white
var cell2 = tableView.cellForRow(at: indexPath) as! DataTableViewCell
cell2.textLabel.textColor = UIColor.white
}
背景更改正常,但文本颜色更改不起作用。
有谁知道为什么以及如何解决这个问题?
我认为与其写这两行:
cell!.textLabel?.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
cell?.textLabel?.textColor = UIColor.white
只写一行如下:
cell.textLabel?.highlightedTextColor = .black
将为您工作正常!
尝试以下任一方法:
// set highlighted color in `tableView cellForRowAt indexPath`
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell?.textLabel?.highlightedTextColor = UIColor.white
}
或尝试这个
class CustomCell: UITableViewCell {
// As an alternate of `tableView cellForRowAt indexPath`, label text highlighted color can be set in both these methods of cell - `awakeFromNib` and `prepareForReuse`
override func awakeFromNib() {
super.awakeFromNib()
self.textLabel?.highlightedTextColor = UIColor.white
}
override func prepareForReuse() {
super.prepareForReuse()
self.textLabel?.highlightedTextColor = UIColor.white
}
// or textColor can be directly set here
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
self.textLabel?.textColor = UIColor.white
}
}
tableView(_:didHighlightRowAt:)
函数是应用程序控制器域的一部分,而设置颜色是视图域的一部分(根据模型—视图—控制器模式)。 为了保持良好的职责分离,您可能需要考虑在控制器外部(即单元本身)中更改颜色。 为此,您将创建一个简单的UITableViewCell
子类,如下所示:
class MyCell: UITableViewCell {
class var reuseIdentifier: String { return "MyCell" }
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
textLabel?.textColor = UIColor.white
} else {
textLabel?.textColor = UIColor.black
}
}
}
这样,单元本身(而不是控制器)将处理其自己的图形表示,这是推荐的方法。
cell.textLabel.highlightedTextColor = [UIColor greencolor];
好的,此代码有效:
override func awakeFromNib () {
super.awakeFromNib ()
// Initialization code
self.titleCell? .xtxtColor = UIColor.black
self.titleCell? .highlightedTextColor = UIColor.white
}
override func setSelected (_ selected: Bool, animated: Bool) {
super.setSelected (selected, animated: animated)
// Configure the view for the selected state
}
override func prepareForReuse () {
super.prepareForReuse ()
self.titleCell? .highlightedTextColor = UIColor.white
}
非常感谢您的帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.