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 🙏
2
Answers
I was able to achieve what you wanted with a custom flow layout.
Here is the result with a regular flow layout
I create a custom flow layout class so that the cells could be in 1 column and the second cell overlaps the first
This seems to work ok for the most part but if I scroll down and come back,the first (red) cell comes in front:
So then I just add the z index in
prepare
function to solve thisAnd now everything works as it should
The full example of this code can be found here
You should create your own UICollectionViewFlowLayout subclass and use the following method to set attributes: