iOS UICollectionViewCells Layout with intersection

2019-04-10 01:27发布

I try to make UICollectionView with cells, that intersect and partially overlay each other as it is done at screenshot: Layout 1 This layout was reached by setting

self.minimumLineSpacing = -100;

at my UICollectionViewFlowLayout subclass. When I scroll down, everything is OK. I see what I want. But when I scroll up, I see another behaviour, not like I expected: Layout 2 So my question is: how can I make my layout look as at the first screen regardless scroll view direction. Note: I have to support both iOS 6 and 7.

Thanks very much for any advices and any help.

2条回答
太酷不给撩
2楼-- · 2019-04-10 01:45

Found another sollution to solve this problem. We need to use UICollectionViewFlowLayout subclass.

@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

Hope that helps someone else.

查看更多
别忘想泡老子
3楼-- · 2019-04-10 02:00

Hmm, interesting. Since the collection view recycles cells, they are continuously added to and removed from the view hierarchy as they move on and off the screen. That being said, it stands to reason and when they are re-added to the view, they are simply added as subviews meaning that when a cell gets recycled, it now has the highest z-index of all of the cells.

One fairly pain-free way to rectify this would be to manually adjust the z position of each cell to be incrementally higher with the index path. That way, lower (y) cells will always appear above (z) the cells above (y) them.

- (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;
}
查看更多
登录 后发表回答