Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UI TableViewCell selected backgroundcolor swift

Tags:

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
    }
like image 907
Peasant coder Avatar asked Mar 03 '15 13:03

Peasant coder


1 Answers

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

cell.selectionStyle = .None

and then set didHighlightRowAtIndexPath...

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

func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .clear
}
like image 195
Cao Yong Avatar answered Oct 27 '22 19:10

Cao Yong