问题描述
我正在尝试通过设置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)
}
}
解决方法
由于我正在尝试在collectionViewCell中显示图像,因此无需设置zPosition,我们可以更改AdjustsImageWhenAncestorFocused属性。我找到了相同的解决方案。
我必须如下设置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)
}
}