I have created a custom UITableViewCell. The table view is showing data fine. What I am stuck in is when user touches cell of tableview, then I want to show the background color of the cell other than the default [blue color] values for highlighting the selection of cell. I use this code but nothing happens:

cell.selectedBackgroundView.backgroundColor=[UIColor blackColor];

Solution 1:

No need for custom cells. If you only want to change the selected color of the cell, you can do this:

Objective-C:

UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor redColor];
[cell setSelectedBackgroundView:bgColorView];

Swift:

let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.red
cell.selectedBackgroundView = bgColorView

Solution 2:

I think you were on the right track, but according to the class definition for selectedBackgroundView:

The default is nil for cells in plain-style tables (UITableViewStylePlain) and non-nil for section-group tables UITableViewStyleGrouped).

Therefore, if you're using a plain-style table, then you'll need to alloc-init a new UIView having your desired background colour and then assign it to selectedBackgroundView.

Alternatively, you could use:

cell.selectionStyle = UITableViewCellSelectionStyleGray;

if all you wanted was a gray background when the cell is selected. Hope this helps.

Solution 3:

Table View Cell selection background color can be set via the Storyboard in Interface Builder:

table view cell selection color None