UITableView Selected Cell Background Color

UITableView Selected Cell Background Color

Swift 5.0
SelectedCellBackgroundColor on the GitHub.

It is easy to change the background color of the selected cell in a table view. Each UITableViewCell has a selectedBackgroundView which is shown when the cell is selected. This view should be set programmatically. The easiest place to do so is in tableView(_:cellForRowAt:) method of the data source object same as below.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "CarCell") as? CarCell else {
            fatalError("There is not such cell in storyboard!")
        }
        
        let backgroundView = UIView()
        backgroundView.backgroundColor = UIColor.systemYellow
        cell.selectedBackgroundView = backgroundView
        
        cell.nameLabel.text = carsModel[indexPath.row]
        return cell
    }

Even though the above code works well, the method tableView(_:cellForRowAt:) is called frequently, for example during scroll operation, and it is not a good place to do things that doing them once is enough. So to increase performance, we can move the selectedBackgroundView code into the cell custom class, awakeFromNib method.

override func awakeFromNib() {
        
        super.awakeFromNib()
        
        let backgroundView = UIView()
        backgroundView.backgroundColor = UIColor.systemYellow
        selectedBackgroundView = backgroundView
    }


Posted

in

by