Custom UI TableViewCell selected backgroundcolor swift

╄→尐↘猪︶ㄣ 提交于 2019-12-02 20:47:24

You've the right method already in there: didSelectRowAtIndexPath. In that method you can call tableView.cellForRowAtIndexPath(indexPath) and get your cell. Than you can set the cell-background to your color:

 func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("Row \(indexPath.row) selected")
        let cell:YourCustomCell = tableView.cellForRowAtIndexPath(indexPath) as YourCell
        cell.backgroundColor = UIColor.redColor()
    }

Or, a better way would be to check in your cellForRowAtIndexPath method, if a cell is selected:

if(cell.selected){
  cell.backgroundColor = UIColor.redColor()
}else{
  cell.backgroundColor = UIColor.clearColor()
}

I have a likeness problem. In your cellForRowAtIndexPath method set:

cell.selectionStyle = .None

and then set didHighlightRowAtIndexPath...

func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
    let cell  = tableView.cellForRowAtIndexPath(indexPath)
    cell!.contentView.backgroundColor = .redColor()
}

func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
        let cell  = tableView.cellForRowAtIndexPath(indexPath)
        cell!.contentView.backgroundColor = .clearColor()
}

My two cents: the proper way of doing it (also visually) is to use the designated view in a (tableView)cell, that is the selectedBackgroundView property. However, you need to initialize it first with UIView()

SWIFT 3.0

override func awakeFromNib() {
    super.awakeFromNib()
    self.selectedBackgroundView = UIView()
    self.selectionStyle = .default // you can also take this line out
}

Then you can use it in your customized cell as follows:

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    self.selectedBackgroundView!.backgroundColor = selected ? .red : nil
}

That's it. Of course you can also integrate the above in your UITableView functions referred to above. Check it out.

Update for Swift 3

This answer is based on Cao Yong answer, and it is intended as an update for Swift 3

For Swift 3, use the following code in your cellForRowAt indexPath method set:

cell.selectionStyle = .none

Then, set it in didHighlightRowAtIndexPath

func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .red
}

func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .clear
}

When you tap a cell, a subviews background color is actually being changed. That subview is 'selectedBackgroundView'. You can override the view of each cell in the cellForRowAtIndexPath TableView delegate method.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

   let cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) 

   let selectedView = UIView()
   selectedView.backgroundColor = UIColor(red: 250/255, green: 250/255, blue:     250/255, alpha: 1.0)
   cell.selectedBackgroundView = selectedView

   return cell
}

Change the color to whatever you like.

To keep your code clean you should think about moving screen design related code for your cells from UITableViewController into a UITableViewCell class.

Your UITableViewController` needs only to set the selected state of the cell as follows:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    guard let cell = tableView.cellForRow(at: indexPath) else { return }
    cell.setSelected(true, animated: true)
}

Your desired customisation can be implemented in a derrived UITableViewCell class by overriding var isSelected. With this solution you could have even different select colors for each cell.

class MyTableViewCell: UITableViewCell
{
    @IBOutlet weak var label:UILabel!

    override var isSelected: Bool
    {
        didSet{
            if (isSelected)
            {
                self.backgroundColor = UIColor.red
                if let label = label
                {
                    label.textColor = UIColor.white
                }
            }
            else
            {
                self.backgroundColor = UIColor.white
                if let label = label
                {
                    label.textColor = UIColor.black
                }
            }
        }
    }
}

The correct (more native & natural) way to do it:

override func awakeFromNib() {
    super.awakeFromNib()
    selectedBackgroundView = UIView()
    selectedBackgroundView?.backgroundColor = .blue
}

Why other approaches are wrong:

  1. Highlight solution: highlight is not select. Highlight doesn't animate as Selection does. It doesn't feel natural as a normal Selection would do
  2. No need to change the color of selectedBackgroundView in setSelected method, because iOS handles the animation for us.
  3. Setting backgroundColor also doesn't behave the same as iOS does it

SWIFT 5 Update

Set the selection style to .none in the cellForRowAT method:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell
    cell.selectionStyle = .none

    return cell
}

Then implement the didHighlightRowAt and the didUnhighlightRowAt methods:

func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .red
}

func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    // Add timer to be able see the effect
    Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false) { (_) in
       cell!.contentView.backgroundColor = .white
    }
}

For tableView==


First Call This method-

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        cell.textLabel?.text = "Show Label"
        cell.backgroundColor = UIColor.redColor()

    }

And than call this method

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        cell.backgroundColor = UIColor.clearColor()
    }

For CollectionView==

1-

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let cell = dateCollectionView.cellForItemAtIndexPath(indexPath) as! DateCollectionViewCell
            cell!.dateLabel.backgroundColor = UIColor.redColor()

 }  

2-

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
        let cell = dateCollectionView.cellForItemAtIndexPath(indexPath) as? DateCollectionViewCell
        cell!.dateLabel.backgroundColor = UIColor.clearColor()
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!