I have a custom tableViewCell. I want to indicate user touch down by highlighting. The cell selection style is UITableViewCellSelectionStyleBlue
. In the parent controller I have set self.clearsSelectionOnViewWillAppear = YES
.
I should be good to go. Nope. Selection still sticks to the cell. What I want is selection indication only for the duration of the touch down. The appearance should immediately return to the unselected appearance on touch up.
How do I do this?
Cheers,
Doug
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Below Swift example uses didHighlightRowAtIndexPath
to change the background color of the cell on touch down and didUnhighlightRowAtIndexPath
to reset the color - see below:
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.backgroundColor = UIColor.greenColor()
}
}
func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.backgroundColor = UIColor.blackColor()
}
}
overwrite - (void)setSelected:(BOOL)selected animate:(BOOL)animated
without calling super
Update Zorayz answer. Swift 5
Set when setup tableView(ViewDidLoad)
tableView.allowsSelection = true
Add this method:
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? SettingCell {
cell.backView.backgroundColor = .red
}
}
func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? SettingCell {
cell.backView.backgroundColor = .green
}
}
Custom cell with xib
class SettingCell: UITableViewCell {
@IBOutlet weak var backView: UIView!
@IBOutlet weak var imageIcon: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var describeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.addSettings()
}
private func addSettings() {
self.contentView.backgroundColor = .white
self.backView.layer.cornerRadius = 12
self.titleLabel.textColor = UIColor(hex: "#101010")
self.describeLabel.textColor = UIColor(hex: "#676767")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setupCell(data: SettingModel) -> SettingCell {
self.imageIcon.image = UIImage(named: data.iconImage)
self.titleLabel.text = data.titleLabel
self.describeLabel.text = data.describeLabel
return self
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With