【问题标题】:CollectionViewCell makes random things while scrollingCollectionViewCell 在滚动时会产生随机的东西
【发布时间】:2014-06-28 15:02:16
【问题描述】:

点击一个单元格后,我的单元格将背景变为黄色。当其背景为黄色时,它将恢复为默认颜色。

一切正常,但如果我开始滚动一些单元格,背景颜色会变为黄色,尽管它没有被选中。不幸的是,它具有随机行为。

我更改了使用alloc init 创建单元格,但现在它抛出了一个错误,上面写着:

cells must be retrieved by calling -dequeueReusableCellWithReuseIdentifier:forIndexPath:

我使用故事板来操作单元格中的元素并像使用它们一样

 UICollectionViewCell *cell = [collectionView
                              dequeueReusableCellWithReuseIdentifier:@"Number Cell"
                              forIndexPath:indexPath];




UILabel *label = (UILabel *)[cell viewWithTag:100];
label.text = [NSString stringWithFormat:@"%i", indexPath.item + 1];

有什么建议吗?

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

    UICollectionViewCell *cell = [collectionView
                                  dequeueReusableCellWithReuseIdentifier:@"Number Cell"
                                  forIndexPath:indexPath];


    UILabel *label = (UILabel *)[cell viewWithTag:100];
    label.text = [NSString stringWithFormat:@"%i", (int)indexPath.item + 1];

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];


        if ([cell.backgroundColor isEqual:[UIColor yellowColor]]) {

            cell.backgroundColor  = [UIColor clearColor];
        } else {    

            cell.backgroundColor  = [UIColor yellowColor];           
        }

}

我猜,

- (void)collectionView:(UICollectionView *)collectionView
    didSelectItemAtIndexPath:(NSIndexPath *)indexPath

每当我点击一个单元格时都会调用它。因此,当颜色清晰时,我将颜色更改为黄色,反之亦然。

【问题讨论】:

    标签: ios uikit uicollectionview uicollectionviewcell


    【解决方案1】:

    如果您在单元格的 setSelected: 方法中设置黄色背景颜色,这应该会自动发生,假设如果有人调用 [cell setSelected:NO],您也将其设置为正常。

    如果这不起作用,您可以在将单元格出列后或在单元格的prepareForReuse: 方法中重置单元格的背景颜色。

    【讨论】:

    • 重用一个单元格会产生非常不可预测的行为。我将一个单元格子类化并使用带有清晰背景颜色的prepareForReuse,效果是它完全清除了所有单元格。所以,我将它与if (self.selected == YES) 一起使用,但没有结果。我想要非常简单的东西 - 选择和取消选择具有背景可视化的单元格。
    • @vaberer,你能举一个最小的例子来说明你正在做什么导致问题吗?
    • @vaberer 正如我在回答的第一部分中所说,如果参数为“是”,则在单元类中简单地覆盖 setSelected: 以将其设置为黄色可能是最简单的,如果参数为“否”则清除。我不明白您为什么要先测试单元格的背景,因为如果用户点击已选择的单元格,它将调用 deselect 方法。集合视图将在 prepareForReuse 中为您调用 setSelected:,因此您只需覆盖 setSelected: 并可以删除您对 didSelectCell... 的实现。
    • 完美!我刚刚添加了self.collectionView.allowsMultipleSelection = YES; 来选择和取消选择多个单元格,一切正常。
    猜你喜欢
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多