Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView not obeying zIndex of UICollectionViewLayoutAttributes

The effect I'm trying to achieve is a kind of sticky header cell. It's important to me that the sticky cell floats over the top of the others. Something a bit like this:

┌──────────┐ 
│          │ 
│  Cell 0  │ 
│          ├┐
└┬─────────┘│
 │  Cell 4  │
 │          │
 └──────────┘
 ┌──────────┐
 │          │
 │  Cell 5  │
 │          │
 └──────────┘
 ┌──────────┐
 │          │
 │  Cell 6  │
 │          │
 └──────────┘

Cell 4, 5 and 6 would normally viewable and I'm constructing the attributes for cell 0 in my UICollectionViewFlowLayout subclass during layoutAttributesForElementsInRect:. All I do is call the super implementation, determine which cell I need to add in and then construct the UICollectionViewLayoutAttributes(forCellWithIndexPath:). I then set the zIndex for it to 1 (default is 0).

The problem I'm getting is that the UICollectionView seems to always ignore the zIndex

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

Now I believe it's possible to visually sort this out using a 3d transform, but that doesn't work for me as I don't want any taps going to the cell which is over the top. So in this example I don't want Cell 4 receiving taps intended for Cell 0.

Does anyone have any ideas? This is on iOS 8.4.

like image 608
earltedly Avatar asked Jul 29 '15 10:07

earltedly


People also ask

How does UICollectionView work?

The collection view presents items onscreen using a cell, which is an instance of the UICollectionViewCell class that your data source configures and provides. In addition to its cells, a collection view can present data using other types of views.

What is a UICollectionView in Swift?

From apple's documentation, UICollectionView is: An object that manages an ordered collection of data items and presents them using customizable layouts. The name and definition makes it clear, it is a way to display a Collection of UI Views in our app.


1 Answers

Updating UICollectionViewLayoutAttributes.zIndex doesn't work due to UIKit bug.

This code does the trick:

// In your UICollectionViewCell subclass:
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
    super.apply(layoutAttributes)
    layer.zPosition = CGFloat(layoutAttributes.zIndex) // or any zIndex you want to set
}
like image 184
Andrey Gordeev Avatar answered Oct 14 '22 15:10

Andrey Gordeev