Search code examples
iosswiftuitableviewuicolor

Swift iOS -How to change TableView Cell Properties for All Visible Cells Already Loaded On Screen Without Reloading Data?


I'm using a splitViewController and on the master side I have a tableView and on the detail side I have whatever info will be shown from the selected cell.

I send a notification from the detail side to the master side to change the color of the textLabels inside the cells after they have already been loaded on the screen (I don't want to reload).

  1. cells are first loaded with black textlabel's

enter image description here

  1. while the cells are still on screen, a notification gets sent, I want change the textLabels to lightGray

enter image description here

  1. while the cells are still on screen, a different notification gets sent and I want to change the textLabels back to black

enter image description here

Everything works fine but the problem is the way I'm doing it now I can only change each individual visible cell separately but I want to change them all at once. If had 10 cells there would be a lot of code so I know there has to be a more efficient way.

@objc fileprivate func changeTextLabelColorToLightGray(){

        let indexPathZero = NSIndexPath(row: 0, section: 0)
        let cellZero = tableView.cellForRow(at: indexPathZero as IndexPath) as! MyCustomCell
        cellZero.textLabel.text = UIColor.lightGray

        let indexPathOne = NSIndexPath(row: 1, section: 0)
        let cellOne = tableView.cellForRow(at: indexPathZero as IndexPath) as! MyCustomCell
        cellOne.textLabel.text = UIColor.lightGray
}

@objc fileprivate func changeTextLabelColorBackToBlack(){

        let indexPathZero = NSIndexPath(row: 0, section: 0)
        let cellZero = tableView.cellForRow(at: indexPathZero as IndexPath) as! MyCustomCell
        cellZero.textLabel.text = UIColor.black

        let indexPathOne = NSIndexPath(row: 1, section: 0)
        let cellOne = tableView.cellForRow(at: indexPathZero as IndexPath) as! MyCustomCell
        cellOne.textLabel.text = UIColor.black
}

How can I do the above and access all the visible cells and change their properties at once instead individually?


Solution

  • You have access to the property visibleCells for UITableView and UICollectionView. Here's an example of what you can do:

        tableView?.visibleCells.forEach { cell in
            if let cell = cell as? YourCell {
                cell.changeTextLabelColorBackToBlack()
            }
        }