2

I am having a hard time preventing color change on my background color for my IBAction button when I select a row in my tableView. The background of my button is set to green, but when I tap the table view cell, it becomes gray. I have tried to change the color through different functions (tableView didSelectRowAtIndexPath etc..). Any ideas on how I would prevent the background of the button to change?

Thanks in advance!

Nirav D
  • 71,513
  • 12
  • 161
  • 183
askaale
  • 1,199
  • 1
  • 23
  • 50

3 Answers3

2

I have faced same problem with button backgroundColor in TableView and solved it this way.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! CustomCell
    cell.button.backgroundColor = UIColor.greenColor()
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • Hi! Thanks for the response. The code is working if I just tap a table view cell. However, if I was to hold the touch, the background color of the button turns gray. Do you have a soultion for this as well? By the way, sorry for the late response. – askaale Oct 17 '16 at 17:09
  • Welcome mate :) – Nirav D Oct 18 '16 at 05:29
2

If you want to disable color change on selection entirely, change the selectionStyle attribute in your custom cell:

selectionStyle = .none
tondo
  • 31
  • 2
0

I solved the problem with the code Nirav provided me above:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! CustomCell
    cell.button.backgroundColor = UIColor.green
}

However, I noticed that the button background color continued to turn gray when I tapped the row, and held the 'tap' without releasing. I solved this by adding the following code as well:

func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! CustomCell
    cell.exploreButton.backgroundColor = UIColor.green

}
askaale
  • 1,199
  • 1
  • 23
  • 50