【问题标题】:UICollectionview Sections/Rows/ArrayUICollectionview 部分/行/数组
【发布时间】:2025-11-22 11:30:01
【问题描述】:

我正在尝试用 UICollectionView 做一些事情。我希望它们居中,但因此我需要创建这样的东西:

(Array consists of 5 items)
X X <- 2 items in section 1
X X <- 2 items in section 2
X   <- 1 item in section 3

但问题是项目没有显示对吗?如果我有 3 个项目。这些项目就像,在第 1 节中,第 1 项和第 2 项。然后在第 2 节中将再次成为第 1 项,而不是我的数组的第 3 项。

这是我的代码:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    float uitkomst = ceilf((float)[arrayDobbel count] / 2) - 1; // Array starts at 0 so need to do - 1

    if (uitkomst == section) {
        return 1; // Last cell
    }
    return 2; //Always 2 cells to each other, not the last section
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    float uitkomst = ceilf((float)[arrayDobbel count] / 2); //Calculate how much sections. Always 2 items / section

    return (int)uitkomst;
}

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

    detailDice *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"dobbelsteenGame" forIndexPath:indexPath];

    cell.layer.cornerRadius = 25;
    cell.layer.backgroundColor = [[UIColor colorWithRed:0.188 green:0.341 blue:0.612 alpha:1.0] CGColor];
    [[cell detaildiceLabel] setText: [NSString stringWithFormat:@"%@", [[arrayDobbel objectAtIndex:indexPath.row] returnRandomOptie]]];

    return cell;
}

谁能帮我在正确的单元格中显示正确的文本?

亲切的问候

【问题讨论】:

  • 你玩sectionrowsection在你的collectionView:cellForItemAtIndexPath:中没有使用

标签: ios objective-c uicollectionview


【解决方案1】:

cellForItemAtIndexPath:

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

    ....
    //since there is 2 items in each section
    int index = 2*indexPath.section + indexPath.row;
    [[cell detaildiceLabel] setText: [NSString stringWithFormat:@"%@", [[arrayDobbel objectAtIndex:index] returnRandomOptie]]];

    return cell;
}

【讨论】: