首页 文章

UICollectionView和滚动程序错误

提问于
浏览
2

我在普通的UIViewController中有一个UICollectionView .

在collectionview中,我为storyboard中的collectionviewcells设计了可重用的UI .

在collectionviewcell的内部有一个标签,显示单元格indexpath.row和5个UIButtons,如果选中,则更改颜色并保持选中状态 .

我已经设置了集合视图,因此如果请求的单元格超过30个,则集合视图将水平翻页,集合视图布局也是水平的 .

应用程序运行良好,正确滚动并正确布局单元格 .

The problem 我有的是当你在集合视图单元中选择例如 button A in cell 1 (假设布局100个单元格)并且在两页(60个单元格)上翻页到 page 3, button A in cell number 75 is selected . 此外,如果滚动到结尾(100个单元格)和 scroll back to page 3 ,单元格编号75中的按钮A的选择时间会更长,但是 button A in cell number 64 is selected .

以下是一些代码片段:cell.m - 控制用户的操作 .

- (IBAction)bubbleButtons:(id)sender {
    for(UIButton *bubbleCell in self.bubbleButtons) {
            if (bubbleCell.touchInside && !bubbleCell.selected) {
                bubbleCell.selected = YES;
            } else if (bubbleCell.touchInside && bubbleCell.selected) {
                bubbleCell.selected = NO;
            }
      }

 }

MainViewContoller.m - 在故事板中设置UICollectionViewCell的单元格

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView 
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        Cell *cell1;
        cell1 =[collectionView dequeueReusableCellWithReuseIdentifier:zCellID
                                                         forIndexPath:indexPath];
        cell1.numMainLabel.text = [NSString stringWithFormat:@"%d |",indexPath.row+1];
        return cell1;

我真的不明白什么是错误或导致这个错误的原因,我假设当视图的新部分变得可见时,视图被重新加载,但这只是一个猜测 . 非常感谢帮助 .

  • 扎克

2 回答

  • 0

    这可能是因为重用了可重用的视图 .

    正确的方法是创建自定义可重用的视图子类 . 并保存那5个按钮的选择 .

    cell1 =[collectionView dequeueReusableCellWithReuseIdentifier:zCellID
    

    这条线可能会或可能不会为您提供一个新单元格,它可能会为您提供之前使用过的单元格 . 因此,您需要在那里更新选择 . 或者它与它重复使用的单元格保持一致 .

  • 2

    Uicollection仅生成当时显示的单元格,因此当单元格从可见视图中消失时,它将被替换为新单元格 .

    因此,当您选择单元格75并向下滚动,直到单元格75不可见时,然后向后滚动回到单元格75,您将生成一个新单元格,其中新按钮由于是新的而未被选中 .

    那么你可以做什么,是保存哪些按钮已经插入,并且在

    • (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

    询问是否需要选择当时显示的按钮..

    希望它的帮助

相关问题