iosswiftuicollectionviewuicollectionviewcellzposition

Changing the zPosition of the collectionView cell in tvOS in Swift


I am trying to bring the focused collectionView cell to the front by setting the zPosition like in the code shown below. But that doesn't seem to have any effect. Please let me know the correct procedure to do it.

 func collectionView(_ collectionView: UICollectionView, didUpdateFocusIn context: UICollectionViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
        if let prevIndexPath = context.previouslyFocusedIndexPath, let cell = collectionView.cellForItem(at: prevIndexPath) {
            cell.contentView.layer.zPosition = 0
        }
        
        if let indexPath = context.nextFocusedIndexPath,
            let cell = collectionView.cellForItem(at: indexPath) {
            cell.contentView.layer.zPosition = 1.0
            collectionView.scrollToItem(at: indexPath, at: [.centeredHorizontally, .centeredVertically], animated: true)
        }
    }

Solution

  • Since i am trying to show an image in the collectionViewCell, instead of setting the zPosition we can change the adjustsImageWhenAncestorFocused property. I found the solution for the same.

    I had to set the adjustsImageWhenAncestorFocused property of the imageview as follows :

    func collectionView(_ collectionView: UICollectionView, didUpdateFocusIn context: UICollectionViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
            if let prevIndexPath = context.previouslyFocusedIndexPath, let cell = collectionView.cellForItem(at: prevIndexPath) {
                           cell.imageView.adjustsImageWhenAncestorFocused = false
            }
            
            if let indexPath = context.nextFocusedIndexPath,
                let cell = collectionView.cellForItem(at: indexPath) {
                           cell.imageView.adjustsImageWhenAncestorFocused = true
                collectionView.scrollToItem(at: indexPath, at: [.centeredHorizontally, .centeredVertically], animated: true)
            }
        }