How to change color of UITableViewCell when selecting?

前端 未结 14 2483
予麋鹿
予麋鹿 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

    0 讨论(0)
  • 2020-12-04 11:44

    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];
    
    0 讨论(0)
提交回复
热议问题