How to alternate row colour in UITableView

Say I have a UITableView with a custom UITableViewCell containing 4 labels, would there be a way to, upon loading the cells into the view with a basic layout, edit them based on the row number that they are in. In my example I would need every other row's text label's text to have one colour, and the other to have a different colour. I am already pretty sure that my answer would involve something like:

bool true = (int) indexpath.row %2 != 0

And then I would set an if statements that changes the colour based on the boolean value. The only thing I don't know is what method I would have to put this in the TableViewSource and how I would be able to access the specific cell's contents and not every cell's contents.

1 answer

  • answered 2018-08-09 00:44 Anil Kumar

    Get indexpath of specific row:

    let indexPath = NSIndexPath(forRow: rowNumber, inSection: 0)
    

    Reload specific cell of the tableview:

    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
    

    Get specific cell of and changes done:

    let cell = tableView.cellForRow(at: indexPath)