Changing background color of selected cell?

后端 未结 30 2972
太阳男子
太阳男子 2020-11-29 00:22

Does anyone know how to change the background color of a cell using UITableViewCell, for each selected cell? I created this UITableViewCell inside the code for TableView.

30条回答
  •  天涯浪人
    2020-11-29 00:41

    SWIFT 5.X
    It also works when accessoryType changed for cell

    extension UITableViewCell{
        var selectedBackgroundColor: UIColor?{
            set{
                let customColorView = UIView()
                customColorView.backgroundColor = newValue
                selectedBackgroundView = customColorView
            }
            get{
                return selectedBackgroundView?.backgroundColor
            }
        }
    }
    

    And in UIViewController use like below...

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! myCell
        cell.selectedBackgroundColor = UIColor.lightGray
        return cell
      }
    

提交回复
热议问题