即使单元格超过数组索引,也要继续向数组中的单元格添加值

时间:2015-12-13 11:54:19

标签: swift uitableview

我在tableView中有10个(最终更多)单元格,我想将单元格视图的背景颜色更改为存储在数组中的4种颜色。

我想循环使用这4种颜色,以便每个第4个单元格的背景颜色是数组中的颜色之一,换句话说......

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

那是阵列。

如何在cellForRowAtIndexPath

中循环显示这些值

这是我的cellForRowAtIndexPath,显然不起作用......

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!
}

我知道我必须循环使用它,但我不知道如果单元格超过数组中的颜色,如何保持循环运行...

为了了解我的意思,设计类似于App YO!在其地址簿VC中。相同的设计理念。

提前多多感谢

1 个答案:

答案 0 :(得分:1)

它应该使用modulo:

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