-1

I have 10 (eventually more) cells in a tableView that I want to change the cell view's background color to 4 colors that are stored in an array.

I want to loop through those 4 colors so that the background color for every 4th cell is one of the colors in the array in other words...

 var viewColors: [UIColor] = [UIColor.purpleColor(), UIColor.blackColor(), UIColor.orangeColor(), UIColor.blueColor()]

That's the array.

How do I loop through these values in the cellForRowAtIndexPath?

This is my cellForRowAtIndexPath which obviously doesn't work...

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell: AddressCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! AddressCell

    if (cell == nil) {

        cell = NSBundle.mainBundle().loadNibNamed("AddressCell", owner: self, options: nil)[0] as? AddressCell

    }


    let contact = contacts[indexPath.row] as CNContact
    cell?.nameLabel!.text = "\(contact.givenName) \(contact.familyName)"

    cell?.view.backgroundColor = viewColors[indexPath.row]

    //how should I loop through this? What would be the correct syntax?

    return cell!
}

I know I have to loop through this, but I have no clue how to keep the loop going even if the cells are more than the colors in the array...

To get an idea of what I mean, the design is similar to what the App YO! has in its Address Book VC. Same design idea.

Thanks a lot in advance

adolfosrs
  • 9,286
  • 5
  • 39
  • 67
Lukesivi
  • 2,206
  • 4
  • 25
  • 43

1 Answers1

1

It should work with modulo:

cell?.view.backgroundColor = viewColors[indexPath.row % viewColors.count]
Fabio Poloni
  • 8,219
  • 5
  • 44
  • 74
  • 1
    @lukesIvi Thanks, here's a great question about how modulus works: http://stackoverflow.com/questions/2664301/how-does-modulus-divison-work – Fabio Poloni Dec 13 '15 at 12:04