Reputation: 550
I am trying to highlight the first cell in my tableview using this code:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
cell.layer.borderWidth = 0
cell.layer.borderColor = nil
cell.layer.borderWidth = 2
cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor
}
}
All seems OK. But when I click on some cell, go to another viewController, and then go back to my cells, somehow the second cell is highlighted already. So I've clicked on my cells several times and found out that after I returned to tableview from another view controller, the next cell is already highlighted (and after N clicks all of my cells become highlighted with border).
How I should fix my code for highlighting ONLY FIRST CELL, even when I go to another controller and return back to my cells?
Upvotes: 2
Views: 418
Reputation: 53181
This code shouldn't really be in your view controller. Create a subclass of UITableViewCell
…
class myCell: UITableViewCell {
var hasBorder = false {
didSet {
layer.borderWidth = hasBorder ? 2 : 0
layer.borderColor = hasBorder ? UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor : nil
}
}
}
Then in your cellForRow atIndexPath
method:
cell.hasBorder = indexPath.row == 0
Upvotes: 1
Reputation: 4265
You have to implement the else
branch and add there the default rendering of the cell.
Something like this:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
cell.layer.borderWidth = 2
cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor
} else {
cell.layer.borderWidth = 0
cell.layer.borderColor = nil
}
}
Upvotes: 1
Reputation: 318894
Cells get reused. When you set any attribute for a given condition, you must always reset that attribute for all other conditions.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
cell.layer.borderWidth = 2
cell.layer.borderColor = UIColor(red:0.38, green:0.69, blue:0.16, alpha:1.0).cgColor
} else {
cell.layer.borderWidth = 0
cell.layer.borderColor = nil
}
}
Upvotes: 2