【问题标题】:iOS UICollectionViewCells Layout with intersection带有交叉点的 iOS UICollectionViewCells 布局
【发布时间】:2013-12-19 14:10:19
【问题描述】:

我尝试使用单元格制作UICollectionView,这些单元格相互交叉并部分重叠,就像在屏幕截图中所做的那样: 这个布局是通过设置实现的

self.minimumLineSpacing = -100;

在我的UICollectionViewFlowLayout 子类中。 当我向下滚动时,一切正常。我看到了我想要的。但是当我向上滚动时,我看到了另一种行为,不像我预期的那样: 所以我的问题是:无论滚动视图方向如何,我怎样才能让我的布局看起来像第一个屏幕。 注意:我必须同时支持 iOS 6 和 7。

非常感谢您的任何建议和帮助。

【问题讨论】:

    标签: ios objective-c uicollectionview uicollectionviewlayout


    【解决方案1】:

    嗯,有趣。由于集合视图循环使用单元格,因此当它们在屏幕上移动时,它们会不断地添加到视图层次结构中或从视图层次结构中移除。话虽如此,这是有道理的,当它们被重新添加到视图中时,它们只是作为子视图添加,这意味着当一个单元格被回收时,它现在具有所有单元格中最高的 z-index。

    纠正此问题的一种相当轻松的方法是手动调整每个单元格的 z 位置,使其随着索引路径逐渐升高。这样,较低 (y) 的单元格将始终显示在 (z) 上方 (y) 单元格的上方。

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *cellID = @"CELLID";
    
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
        if (cell.layer.zPosition != indexPath.row) {
            [cell.layer setZPosition:indexPath.row];
        }
    
        return cell;
    }
    

    【讨论】:

    • 完美!非常感谢。看来,它可以按我的意愿工作!
    • 经过详细测试,我发现此代码正确显示单元格重叠,但实际上这不会改变顺序。有时滚动后它会选择另一个单元格下的单元格...
    【解决方案2】:

    找到另一个解决方案来解决这个问题。我们需要使用UICollectionViewFlowLayout 子类。

    @interface MyFlowLayout : UICollectionViewFlowLayout
    @end
    
    @implementation MyFlowLayout
    
    - (void)prepareLayout {
        [super prepareLayout];
        // This allows us to make intersection and overlapping
        self.minimumLineSpacing = -100;
    }
    
    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
    {
        NSArray *layoutAttributes = [super layoutAttributesForElementsInRect:rect];
        for (UICollectionViewLayoutAttributes *currentLayoutAttributes in layoutAttributes) {
            // Change zIndex allows us to change not only visible position, but logic too
            currentLayoutAttributes.zIndex = currentLayoutAttributes.indexPath.row;
        }
        return layoutAttributes;
    }
    
    @end
    

    希望对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 2015-06-05
      • 2011-12-16
      相关资源
      最近更新 更多