I have a menu like so:
The normal (unselected) state for each cell is an image, the selected s
iOS 8.0 (and later) using Swift
Swift 2
override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
var cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.contentView.backgroundColor = UIColor.orangeColor()
cell?.backgroundColor = UIColor.orangeColor()
}
override func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
var cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.contentView.backgroundColor = UIColor.blackColor()
cell?.backgroundColor = UIColor.blackColor()
}
Swift 3
override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.contentView.backgroundColor = UIColor.orange
cell?.backgroundColor = UIColor.orange
}
override func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.contentView.backgroundColor = UIColor.black
cell?.backgroundColor = UIColor.black
}
Using Objective C, Change Selected Cell Background color other than defaults. No need to create custom cells.
If you only want to change the selected color of the cell, you can do this, Be aware that for this to work, in the Storyboard (or XIB file) you must select a Selected Background colour other than None. Just add following code in UITableView Delegate method : tableView cellForRowAtIndexPath:
UIView *bgColor = [[UIView alloc] init];
bgColor.backgroundColor = [UIColor yellowColor];
[cell setSelectedBackgroundView:bgColor];