How to change UICollectionView zIndex?

2019-08-05 18:31发布

问题:

Check the image below. I need to highlight the focused cell such that it is above all the cells in collectionView.
I know I have to change the zIndex of the focused cell. How to do that?
I need the logic. My code is in objective-c.

This is for tvOS but iOS code will also work here I guess.

回答1:

Have you tried setting value for cell.layer.zPosition?



回答2:

Try manually applying layer.zPosition to be the zIndex in applyLayoutAttributes: method of UICollectionViewCell subclass:

- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    [super applyLayoutAttributes:layoutAttributes];
    self.layer.zPosition = layoutAttributes.zIndex;
}


回答3:

You need to create a custom collection view flow layout. Compute the zIndex based on the collection view's scroll position or visible rect. The sample class is shown below.

final class CustomCollectionViewLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributes = super.layoutAttributesForElements(in: rect)
        attributes?.forEach {
            $0.zIndex = 0 //Compute and set
        }
        return attributes
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attribute = super.layoutAttributesForItem(at: indexPath)
        attribute?.zIndex = 0 //Compute and set
        return attribute
    }
}


回答4:

Maybe set the z-position of collection view to -2, unhighlight to -1 and highlight to 0