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?
In iOS 7, what worked for me is to override
setSelected:animated:
in theUITableViewCell
subclass, but contrary to @Brooks' tip, I called[super setSelected:selected animated:animated]
.This lets me keep the system's default selection animation when the user taps on the cell, and also to deselect it in the table view delegate's
didSelectRowAtIndexPath:
.From that you said you built a tableViewCell using IB, I'd like to check whether you are adding your view as a subview of
contentView
of UITableViewCell, notview
. The content view is the default superview for content displayed by the cell.From the reference:
You need to override the next two methods in your custom cell:
Note that:
[super setSelected:animated:]
and[super setHighlighted:animated:]
in the beginning of your custom implementation or correspond methods;UITableViewCellSelectionStyleNone
selectionStyle for your custom cell, to disable any defaultUITableViewCell
styling;Here the example of the implementation:
The
contentView
is the property ofUITableViewCell
that is appeared in iOS 7. Note that you can use your own cell's child view or views instead of it.You can change the behavior of the tableViewCell by overriding the function setHighlighted in UITableViewCell class (you will need to inherit from it). Example of my code where I change the background image of my cell :
You can also change the selection mode to gray, blue or none in the interface builder.
Previously I have done as @P5ycH0 said (1x1 image stretched), but following @Brooks I figured that overriding
-(void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
in my customUITableViewCell
implementation and resetting the the background colors after calling[super setHighlighted:highlighted animated:animated];
keeps my background colors when the cell is selected/highlighted