Ios 使用两个数组的UITableView

Ios 使用两个数组的UITableView,ios,swift,uitableview,Ios,Swift,Uitableview,我试图将两个数组中的值加载到UITableView中,这导致数组索引超出范围错误 1.categories数组包含60个元素,我正在使用此数组设置cell.textlab.text 2.colorsArray数组包含5个UIColor元素,我用它来设置单元格。backgroundColor 我试着重复这5种颜色 代码: 致命错误:数组索引超出范围 我想我需要让色彩光线有60个元素。代码中有没有这样做的方法 我试过了 var categories = category.count for

我试图将两个数组中的值加载到UITableView中,这导致
数组索引超出范围
错误

1.
categories
数组包含60个元素,我正在使用此数组设置
cell.textlab.text

2.
colorsArray
数组包含5个UIColor元素,我用它来设置
单元格。backgroundColor

我试着重复这5种颜色

代码:

致命错误:数组索引超出范围

我想我需要让色彩光线有60个元素。代码中有没有这样做的方法

我试过了

var categories = category.count
     for (i=0;i<categories;i++) {
        colorArray.append(colorArray[i])
}
var categories=category.count
对于(i=0;i试试这个

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellID = "cell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel!.text = category.books[indexPath.row]
    cell.backgroundColor = colorArray[indexPath.row % 5]
        return cell
}

如果您希望在向表视图添加行时为每个单元格重复一系列背景色,则可以使用余数运算符(%)将索引保留在colorArray的范围内:


cell.backgroundColor=colorArray[indexPath.row%5]

您想在这里实现什么?索引路径有时会是59,而颜色数组只有5个元素。您可以从tableViewHi调用另一个函数。我希望我的
UITableCell
根据索引处UIColor的值具有不同的颜色。@Statik:了解moldulo操作永远不会忘记它!Thanks!正是我想要达到的效果。谢谢。因为答案中没有解释,所以添加的
%5
用于获得X的剩余部分除以5。这将确保最高计数为5,因此数组不会越界。@Statik,所以您希望表视图单元格的颜色在5之间循环重复使用不同的颜色?你能编辑你的问题使其清晰吗?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellID = "cell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel!.text = category.books[indexPath.row]
    cell.backgroundColor = colorArray[indexPath.row % 5]
        return cell
}