Search code examples
iosuitableviewswiftuibackgroundcolor

Color alternate UITableViewCell in a UITableView?


I was trying to color alternate tableCell in a Table View using this link to color cell with this code:

func colorForIndex(index: Int) -> UIColor 
{

    let itemCount = stnRepos.count - 1
    let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6
    return UIColor(red: 0.80, green: color, blue: 0.0, alpha: 1.0)
}

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath) 
{
        var count = stnRepos.count
        for (var i = 0; i<=count; i++)
        {
            if (i % 2 == 0)
            {
                cell.backgroundColor = colorForIndex(indexPath.row)
                println(i)
            }
        }
}

but ended up coloring all the cell as shown in the link.


Solution

  • I am not sure if I understand what you are trying to do but, the code bellow will just color (using your function) the even cell and paint in white the odd ones

    func colorForIndex(index: Int) -> UIColor 
    {
        let itemCount = stnRepos.count - 1
        let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6
        return UIColor(red: 0.80, green: color, blue: 0.0, alpha: 1.0)
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
        forRowAtIndexPath indexPath: NSIndexPath) 
    {        
        if (indexPath.row % 2 == 0)
        {
            cell.backgroundColor = colorForIndex(indexPath.row)
        } else {
            cell.backgroundColor = UIColor.whiteColor()()
        }
    }
    

    ps, the code does not have any the dequeuing and the need and grid from the cells just exemplify the logic to paint the even cell while scaping the odd ones. I hope that helps you