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

时间:2016-04-21 17:30:41

标签: swift uicollectionviewcell tvos

我正在尝试构建我的tvOS UI,使其看起来与Apple TV主屏幕类似。当您专注于某个应用时,会在后台显示较大的图像。 (顶部货架区域)。问题是,当我调用didUpdateFocusInContext方法时,背景图像会像它应该的那样改变,但只有在导航通过collectionviewcells时才会改变。一旦我将焦点放在标签栏上,应用程序就会崩溃并显示错误:

  

无法将“UITabBarButton”类型的值转换为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])
}

1 个答案:

答案 0 :(得分:1)

这是因为你强迫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!时要小心。