首页 > 解决方案 > 在 Swift 中更改 tvOS 中 collectionView 单元格的 zPosition

问题描述

我试图通过设置 zPosition 将集中的 collectionView 单元格放在前面,如下所示的代码。但这似乎没有任何效果。请让我知道执行此操作的正确程序。

 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)
        }
    }

标签: iosswiftuicollectionviewuicollectionviewcellzposition

解决方案


由于我试图在 collectionViewCell 中显示图像,因此我们可以更改 adjustsImageWhenAncestorFocused 属性,而不是设置 zPosition。我找到了相同的解决方案。

我必须将 imageview 的 adjustsImageWhenAncestorFocused 属性设置如下:

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)
        }
    }

推荐阅读