UITableViewCell selectedBackgroundView's color not visible when building on iOS 13

后端 未结 3 444
旧巷少年郎
旧巷少年郎 2021-01-05 03:17

I have given a tableview cell a color on selection in cellForRowAtIndexPath using

    let backgroundView = UIView()
    backgroundView.backgroun         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-05 04:08

    I had the same problem, my solutions is:

    TableViewController:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(withIdentifier: "testCell")! as! TestCell
    
        // Turn off selection style for iOS12, iOS11, etc...  
        cell.selectionStyle = .none
    
        return cell
    }
    

    Cell Class (I have a UIView inside cell's ContentView):

    class TestCell: UITableViewCell {
    
        @IBOutlet weak var testCellBackgroundView: UIView!
    
        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
    
            if selected {
                contentView.backgroundColor = UIColor.white
                testCellBackgroundView.backgroundColor = UIColor.red
            } else { 
                contentView.backgroundColor = UIColor.white
                testCellBackgroundView.backgroundColor = UIColor.green // default background color
            }
        }
    
        // You may change highlighted color of a cell the same way
        override func setHighlighted(_ highlighted: Bool, animated: Bool) {
            super.setHighlighted(highlighted, animated: animated)
    
            if highlighted {
                contentView.backgroundColor = UIColor.white
                testCellBackgroundView.backgroundColor = UIColor.red
            } else {
                contentView.backgroundColor = UIColor.white
                testCellBackgroundView.backgroundColor = UIColor.green
            }
        }   
    }
    

    Note: this is my first answer at stackoverflow, please check if it's correct.

提交回复
热议问题