Reputation: 767
When I select on a cell on my table view, it changes into this white color. I want to change it.
I tried using an if statement but it didn't work.
Here is the code that I used.
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
}
Upvotes: 7
Views: 14823
Reputation: 115
you can set the Selected Background view in awakeFromNib method
class MyCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
selectedBackgroundView = {
let view = UIView.init()
view.backgroundColor = .white
return view
}()
}
}
Upvotes: 3
Reputation: 726
In your UITableViewCell
class use following code for change selected cell background view color
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
}
}
Upvotes: -1
Reputation: 745
You can do either one of this -
For example: If you change it to UITableViewCellSelectionStyleGray, it will be gray.
cell.selectionStyle = UITableViewCellSelectionStyleGray;
Change the selectedBackgroundView property.
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView
swift 4 correction:
cell.selectionStyle = UITableViewCellSelectionStyle.gray
Upvotes: 18
Reputation: 984
You can do background color change in either your "willSelect" or "didSelect" method. For example:
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = tableView.cellForRow(at: indexPath)!
cell.contentView.superview?.backgroundColor = UIColor.blue
return indexPath
}
Upvotes: 0