I have a simple tableViewCell build in interface builder. It contains a UIView which contains an image. Now, when I select the cell, the default blue selection background is shown, but the backgroundColor of my UIView is gone.
My UITableViewCell's implementation file doesn't do anything special. It just init's & returns self and all I do in setSelected is call super.
How do I get my UIView backgroundColor to show when the tableView is selected?
Here's my take on it. I have a subclass that all my cell inherit from, so that's the way I do it to avoid the background change in my UIImageViews:
This automaticlly fix the issue for all
UIImageView
.Swift 4
In your UITableViewCell class:
Related to @Brooks's answer, this is what I did to make it work in Swift and iOS8/iOS9.
setSelected
andsetHighlighted
contentView.backgroundColor
, because it does not have to span over the whole width of the cell (i.e. accessories).Use the
backgroundColor
of the cell itself, and set it accordingly.The problem here is that the [super] implementation of
sets all the background colors in the UITableViewCell to rgba(0,0,0,0). Why? Perhaps to make us all sweat?
It is not that entire views disappear (as evidenced by the fact that if you change the views layer border properties, those are retained)
Here is the sequence of function calls that results from touching a cell
So your options are to
Unfortunately re-asserting the background colors in setHighlighted does nothing because setHighlighted is called before all the background colors get set to [r:0 b:0 g:0 a:0] by the first call to setSelected.
//TODO: Give a great description of how to override setSelected (stay tuned)
When your
UITableViewCell
is selected, there are two states you should pay attention to:Highlighted
andSelected
.So, for scenarios that you have a custom cell class which is subclass of
UITableViewCell
, you can easily override these two methods to avoid this situation(Swift):Just spent some time on this weird issue. I did not want to set UITableViewCellSelectionStyleNone style to preserve nice animation when my row was selected. But none of suggested ideas worked for me - I was trying to override setSelected and setHighlighted and set my subview backgroundColor there - it was keeping resetting by iOS and still blinking (new color -> old color). For me the fix was quite simple. When my row is selected another view controller is pushed, user chooses some option on that screen and delegate is called where I change the color based on user selection. In this delegate I just do [cell setSelected:NO animated:NO] for my cell. (I have static UITableViewController and have outlets to cells). You could probably deselect cell in didSelect method but in my case I'm using segues.