I have 2 Table Views with custom Table View Cells, where selecting a cell in the first Table View segues to the 2nd. What I'm trying to achieve is, when you select a cell in the 2nd view, a red border is added and if you go back to the 1st view and return to the 2nd, the cell still has a border.

Before using custom Table View Cells, I tested on 2 Table View Controllers and the code worked; however, it doesn't with custom Table View Cells.

Here is the code I used for Table View Controllers (secondCategory is a class that holds the indexpath of the selected cell):

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath)
    cell?.selectionStyle = UITableViewCell.SelectionStyle.none
    cell?.layer.borderWidth = 3.0
    cell?.layer.borderColor = UIColor.red.cgColor
    secondCategory.currentSelection = indexPath

}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    if  secondCategory.currentSelection != nil {
        let cell = tableView.cellForRow(at: secondCategory.currentSelection!)
        cell!.selectionStyle = UITableViewCell.SelectionStyle.none
        cell!.layer.borderWidth = 3.0
        cell!.layer.borderColor = UIColor.red.cgColor
    }
}

Below is the code for the custom Table View Cells (in viewWillAppear, I use tableView(tableView: UITableView, cellForRowAt: IndexPath) because tableView.cellForRow(at: IndexPath) returns nil):

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath)
    cell?.selectionStyle = UITableViewCell.SelectionStyle.none
    cell?.layer.borderWidth = 3.0
    cell?.layer.borderColor = UIColor.red.cgColor
    secondCategory.currentSelection = indexPath
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    if secondCategory.currentSelection != nil {
        let currentCell = tableView(secondTable, cellForRowAt: secondCategory.currentSelection!)
        currentCell.selectionStyle = UITableViewCell.SelectionStyle.none
        currentCell.layer.borderWidth = 3.0
        currentCell.layer.borderColor = UIColor.red.cgColor
    }
}

Can someone please tell me why the code for the custom Table View Cells doesn't work?

Related posts

Recent Viewed