【问题标题】:UICollectionView top cell from zIndex not selected with overlapping cells来自 zIndex 的 UICollectionView 顶部单元格未选择重叠单元格
【发布时间】:2014-03-17 06:18:03
【问题描述】:

我有一个UICollectionView,其中有许多相互重叠的单元格。

我将他们的zIndex 设置在UICollectionViewLayout 子类和UICollectionViewLayoutAttributes 中,因此它们在视觉上以所需的顺序出现。 当点击单元格的重叠区域时,通过collectionView:didSelectItemAtIndexPath: 方法,zIndex 更高的单元格会按预期工作。

我转换到UICollectionViewFlowLayout 子类,当我转换回第一个UICollectionViewLayout 子类时,在点击重叠区域时并不总是选择具有更高zIndex 的单元格。

进一步调查显示UICollectionViewCells 在UICollectionView 子视图中的顺序决定了哪个单元格被点击。

我已经编写了一个重新排序子视图的方法,但这似乎有点不合时宜。

有没有更好的方法让UICollectionView 单元格根据单元格的视觉外观返回collectionView:didSelectItemAtIndexPath: 中的预期索引路径?

【问题讨论】:

    标签: ios iphone objective-c uicollectionview z-index


    【解决方案1】:

    根据我的测试,布局到布局的转换似乎忽略了推送视图控制器布局的zIndex 属性。这闻起来像个虫子。您可以通过在视图控制器出现后重新加载来解决此问题:

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
    
        // Reloading will clear selection, so we remember which index paths are selected before reload
        NSArray *selectedIndexPaths = self.collectionView.indexPathsForSelectedItems;
        NSIndexSet *allSections = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.collectionView.numberOfSections)];
    
        [self.collectionView performBatchUpdates:^{
    
            // First, reload to correct the zOrder
            [self.collectionView reloadSections:allSections];
    
            // Then, re-select the index paths
            if (selectedIndexPaths.count)
            {
                for (NSIndexPath *indexPath in selectedIndexPaths)
                {
                    [self.collectionView selectItemAtIndexPath:indexPath
                                                      animated:YES
                                                scrollPosition:UICollectionViewScrollPositionNone];
                }
            }
        } completion:nil];
    }
    

    这仍然是一个 hack,但没有手动重新排序集合视图的子视图那么混乱。

    【讨论】:

    • 太棒了!我还添加了 [UIView setAnimationsEnabled:NO];之前和 [UIView setAnimationsEnabled:YES];在完成块中,这样单元格就不会淡入淡出。
    • 很高兴这有帮助。您也可以使用 [self.collectionView reloadData] 而不是 reloadSections: 来重新加载而无需动画 - 只是代码少了一点 :)
    【解决方案2】:

    这应该是正确的方法:https://stackoverflow.com/a/40010956/1032900 在 viewDidAppear 中重新加载可能会导致不必要的重新加载

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多