UITableView set background color

Question!

I change the background color of the UITableViewCells in the tableView:cellForRowAtIndexPath method

    if(indexPath.row % 2 == 0){
        cell.backgroundColor = ...
    } else{
        cell.backgroundColor = ...
    }

But that only change the color of the cell amount specified in tableView:numberOfRowsInSection (As seen in the attached picture, there are white cells after the first four)

Is it possible to change the color of all cells that are displayed on screen?

enter image description here

By : Sp0tlight


Answers

For SWIFT

Thanks to @Irshad Qureshi I was able to get alternating background colors for my prototype cells by adding the following in my cellForRowAtIndexPath:

if (indexPath.row % 2 == 0)
    {
        cell!.backgroundColor = UIColor.groupTableViewBackgroundColor()
    }
    else
    {
        cell!.backgroundColor = UIColor.whiteColor()
    }


You need to set the tableview's backgroundView to nil and its backgroundColor to the desired color.

By : NRitH


I used this to color alternate cell in a table view

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath) {

        if (indexPath.row % 2 == 0)
        {
            cell.backgroundColor = UIColor.grayColor()
        }
        else
        {
            cell.backgroundColor = UIColor.whiteColor()
        }
}


This video can help you solving your question :)
By: admin