[英]How to change selected color for table view cell?
当我在表格视图上选择一个单元格时,它会变成这种白色。 我想改变它。
我尝试使用 if 语句,但没有用。
这是我使用的代码。
override func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
if cell.isSelected == true {
cell.backgroundColor = .blue
} else {
cell.backgroundColor = .red
}
return cell
}
您可以执行以下任一操作-
例如:如果将其更改为 UITableViewCellSelectionStyleGray,它将是灰色的。
cell.selectionStyle = UITableViewCellSelectionStyleGray;
更改 selectedBackgroundView 属性。
let bgColorView = UIView() bgColorView.backgroundColor = UIColor.red cell.selectedBackgroundView = bgColorView
swift 4 更正:
cell.selectionStyle = UITableViewCellSelectionStyle.gray
也许你需要这个:
cell.selectedBackgroundView
您可以在awakeFromNib 方法中设置Selected Background 视图
class MyCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
selectedBackgroundView = {
let view = UIView.init()
view.backgroundColor = .white
return view
}()
}
}
您可以在“willSelect”或“didSelect”方法中更改背景颜色。 例如:
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = tableView.cellForRow(at: indexPath)!
cell.contentView.superview?.backgroundColor = UIColor.blue
return indexPath
}
在您的UITableViewCell
类中,使用以下代码更改选定的单元格背景视图颜色
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
self.contentView.backgroundColor = UIColor.red
} else {
self.contentView.backgroundColor = UIColor.white
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.