How to change color of UITableViewCell when selecting?

前端 未结 14 2542
予麋鹿
予麋鹿 2020-12-04 10:59

I have a menu like so:

\"Menu\"

The normal (unselected) state for each cell is an image, the selected s

14条回答
  •  余生分开走
    2020-12-04 11:42

    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
    }
    

    enter image description here

提交回复
热议问题