tvOS 检查当前聚焦的 ui 元素是否是 CollectionViewCell

tvOS checking if current focused ui element is a CollectionViewCell

我正在尝试让我的 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! 任何东西时都要小心。