Search code examples
iosswiftlayout

In UICollectionView not obeying zIndex of UICollectionViewLayoutAttributes


I'm trying to make the top cell of the collection be behind all the other cells by the zIndex factor

┌──────────┐ 
│          │ 
│  Cell 0  │ 
│┌─────────┴┐
└┤          │
 │  Cell 4  │
 │          │
 └──────────┘
 ┌──────────┐
 │          │
 │  Cell 5  │
 │          │
 └──────────┘
 ┌──────────┐
 │          │
 │  Cell 6  │
 │          │
 └──────────┘

In custom layout in method prepare I add Zindex as follows

override func prepare() {
  super.prepare()
  /// Some code
  
  let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
  attributes.zIndex = zIndex
  
  /// Some code
}

Next, I add the activation of this zIndex in UICollectionViewCell

override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
    super.apply(layoutAttributes)
    layer.zPosition = CGFloat(layoutAttributes.zIndex)
}

When reusing a cell. The topmost cell, which should be in the background, becomes in the foreground

Tell me who faced this problem. What am I doing wrong 🙏


Solution

  • You should create your own UICollectionViewFlowLayout subclass and use the following method to set attributes:

        override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)
        let backMostCellIndex = 0
        
        guard  let attributes = attributes else {
            return nil
        }
    
        for attribute in attributes {
            if attribute.indexPath.item == backMostCellIndex {
                attribute.zIndex = 0
            } else {
                attribute.zIndex = 1
            }
        }
        return attributes
    }