Ios 如何在UICollectionview中标识特定单元格

Ios 如何在UICollectionview中标识特定单元格,ios,objective-c,uicollectionview,Ios,Objective C,Uicollectionview,我想为单元格1、单元格4、单元格7、…n设置颜色黑色,为单元格2、单元格5、单元格8、…n设置颜色 注意:单元格的数量不是固定的。 如何实现这一点?我假设您的CellForItemIndexPath知道如何从nsIndepath获取传递给方法的单元格编号(即1,2,3,4)。然后,您可以通过获得除3的余数来决定使用什么颜色,如下所示: // Decode index path into cell number from your picture int cellNumber = [self ge

我想为单元格1、单元格4、单元格7、…n设置颜色黑色单元格2、单元格5、单元格8、…n设置颜色 注意:单元格的数量不是固定的。


如何实现这一点?

我假设您的
CellForItemIndexPath
知道如何从
nsIndepath
获取传递给方法的单元格编号(即
1
2
3
4
)。然后,您可以通过获得除3的余数来决定使用什么颜色,如下所示:

// Decode index path into cell number from your picture
int cellNumber = [self getCellNumberFromIndexPath:indexPath];
// Figure out the color
if (cellNumber % 3 == 1) {
    // 1, 4, 7, etc
    ... // Use black color
} else if (cellNumber % 3 == 2) {
    // 2, 5, 8, etc
    ... // Use white color
}

正如您在奇数/偶数(使用n%2==0 | 1)条件下所做的那样

这里,你希望每三个单元都有一个。因此,您可以使用3而不是2来修改奇偶逻辑

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    // .... YOUR CURRENT CODE

    // Color change as you wanted it.,,

    if (YOUR_CELL_INDEX % 3 == 0) {
         cell.backgroundColor = [UIColor whiteColor];
    } else { YOUR_CELL_INDEX % 3 == 1) {
         cell.backgroundColor = [UIColor blackColor];
    } else {
         cell.backgroundColor = // Your choice of color....
    }

    // .... REST OF YOUR CODE & return cell;
}
您可以添加为

 if indexPath.item % 3 == 0
        {
            cell.backgroundColor = UIColor.greenColor()

        }
        else if indexPath.item % 3 == 1{
            cell.backgroundColor = UIColor.WhiteColor()

        }

它们是静态单元格吗?不,所有单元格都是动态的。所以,您要更改奇数和偶数单元格的背景色。我说的对吗?不,我不想换奇偶单元格。请再次阅读我的问题。是否有任何数据需要更改背景颜色?谢谢,这是有效的。此答案适用于自定义单元格的特定单元格项目