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

标签 swift uicollectionviewcell tvos

我正在尝试构建我的 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/

相关文章:

ios - 如何在 iOS 中以编程方式预选多选 UITableView 中的单元格

ios - Swift 3 - 如何从 super View 以及数组中删除所有 subview

swift - 需要使用 UICollectionViewLayout 进行 UICollectionViewCell 填充

tvos - 如何让 tvOS 知道不启动屏幕保护程序

ios - xcodebuild 在仅请求 tvOS 时同时构建 iOS 和 tvOS 目标

swift - Swift 中的 IMAAdsLoader 错误但不是 Objective C

swift - 如何从 UIViewController 访问 SKScene 中的方法

ios - 连接 UISlider 和 UITextField 选择正确的数据 - 简单的贷款分期计算器

ios - 关于 UICollectionView 的查询

ios - 选择/取消选择单元格的 UICollectionView 问题