UICollectionView 棋盘式网格布局

3
我需要实现一个象棋风格的网格视图,以显示某些径向进度条。 enter image description here 我使用了一些低效的算法来创建这个网格,因为UiCollectionView不使用行和列,它依然可以工作。但是当用户将集合滚动到极限时,集合的“行”从屏幕上消失,当用户释放屏幕并重新出现UICollectionViewCell时,它们会切换颜色。
我知道切换是通过BOOL值实现的,但我不知道如何解决这个问题。
以下是我的算法(我有两种不同的UICollectionViewCells,每种颜色一个)
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"Cell";
    static NSString *identifierPair = @"CellPair";
    UICollectionViewCell *cell ;
    UILabel *title;

    //...Creating the circle progress bar....


    if ((indexPath.item % 2) == 0) {
        if (isPair) {
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifierPair forIndexPath:indexPath];
            isPair = NO;
            title = (UILabel *)[cell viewWithTag:12];
        }
        else
        {
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
            isPair = YES;
            title = (UILabel *)[cell viewWithTag:11];

        }

    }
    else {
        if (isUneven) {
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifierPair forIndexPath:indexPath];
            isUneven = NO;
            title = (UILabel *)[cell viewWithTag:12];
        }
        else
        {
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
            isUneven = YES;
            title = (UILabel *)[cell viewWithTag:11];
        }
    }


    //...Setting the name to the cell....

    return cell;
}

计数是否在改变?当它们达到100%时,您是否正在删除它们?当添加或删除行时,您是否更新所有行?您是否只想始终在浅色和深色之间交替(例如,偶数为浅色,奇数为深色)? - Marcus Adams
这些圆圈是静态的(我只是用它来向用户显示信息),它们不会被用户删除或添加。 - Sonia Casas
2个回答

2

这似乎更像是在UICollectionView内部使用单个方格背景,但由于我不确定是否可行,您可以尝试以下方法:

+ (BOOL)checkersCellAtIndexIsDark:(NSIndexPath *)indexPath {
    NSInteger squareIndex = indexPath.item % 4;
    return (squareIndex == 0 || squareIndex == 3);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    cell.backgroundColor = ([[self class] checkersCellAtIndexIsDark:indexPath])? [UIColor orangeColor] : [UIColor yellowColor];

    // Set other things

    return cell;
}

我不明白为什么你会在不同的背景下使用不同的reuseIdentifiers和titleLabels,因为从屏幕上看不出来,但是你可以随时编辑这段代码。


直到现在我才看到,将它除以4就能解决所有问题。非常感谢! - Sonia Casas
我曾经因绝望而使用了不同的重用标识符!我删除了一个原型单元格。 - Sonia Casas

0
你不需要使用两个不同的单元格来更改背景颜色。 你只需要设置默认的背景颜色,当indexPath.item是偶数时,只需为单元格背景设置另一种颜色即可。 但是重要的是先设置默认颜色,否则你会得到相同的结果。

如果我只在indexPath.item为偶数时更改背景,那么我将在一列上拥有全米色的背景,而在另一列上为棕色......因为集合按此方式工作:0 1 2 3 4 5 6 7 - Sonia Casas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接