Search code examples
swiftuitableviewselected

Custom UI TableViewCell selected backgroundcolor swift


I am trying to change the appearance of a custom selected TableViewCell using Swift.

Do I need to do it via the designer or programmatically?

I tried the following:

enter image description here

And here is my code:

@IBOutlet var tableView: UITableView!


    var tableData: [String] = ["One", "Two", "Three", "Four"]

    override func viewDidLoad() {
        super.viewDidLoad()


        // Register custom cell
        var nib = UINib(nibName: "vwTblCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: "cell")

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tableData.count
    }

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

        var cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as TblCell

        cell.lblCarName.text = tableData[indexPath.row]
        cell.imgCarName.image = UIImage(named: tableData[indexPath.row])

        return cell

    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("Row \(indexPath.row) selected")
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 70
    }

Solution

  • 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()
    }