我正在尝试构建我的 tvOS UI,使其看起来与 Apple TV 主屏幕类似。当您专注于某个应用程序时,背景中会显示更大的图像。 (顶部货架区域)。问题是,当我调用 didUpdateFocusInContext 方法时,背景图像会按应有的方式发生变化,但仅在浏览 collectionviewcells 时发生。一旦我将焦点放在标签栏上,应用程序就会崩溃并出现错误:
Could not cast value of type 'UITabBarButton' to CustomCollectionViewCell'.
我想我只是不知道如何检查聚焦的 ui 元素是否是 CustomCollectionViewCell。 这是我所拥有的:
func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
let cell: CustomCollectionViewCell = context.nextFocusedView as! CustomCollectionViewCell
let indexPath: NSIndexPath? = self.collectionView.indexPathForCell(cell)
mainImageView.image = UIImage(named: images[indexPath!.row])
}
最佳答案
这是因为您将 context.nextFocusedView
强制转换为 CustomCollectionViewCell
。
您可以通过检查 context.nextFocusedView
是否确实是您期望的类型来避免崩溃,然后才继续执行您想做的任何操作:
func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
if let cell = context.nextFocusedView as? CustomCollectionViewCell {
let indexPath: NSIndexPath? = self.collectionView.indexPathForCell(cell)
mainImageView.image = UIImage(named: images[indexPath!.row])
}
}
一般来说,在强制展开 (!
) 或强制转换 as!
任何内容时要小心。
关于swift - tvOS 检查当前聚焦的 ui 元素是否是 CollectionViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36776668/