如何让父母'使用swift-tvOS在UIcollectionview单元格中聚焦的单元格

时间:2017-01-17 14:49:27

标签: swift uicollectionview uicollectionviewcell tvos

我为我的tvOS应用程序制作了某种Netflix布局,其中包含几个名为featuredCollectionViewstandardCollectionView的集合视图。

我有一个包含当前聚焦单元格的变量。我唯一想要的是获取所选单元格的当前集合视图。任何人都可以帮我吗?

代码

func pressedThePlayPauseButton() {

   if let focusedCell = UIScreen.main.focusedView as? UICollectionViewCell{

       let collectionViewOfFocusedCell = ...

1 个答案:

答案 0 :(得分:1)

您始终可以沿视图层次结构向上走:

    var parentCollectionView = self.superview
    while parentCollectionView is UICollectionView != true {
        parentCollectionView = parentCollectionView?.superview
    }

如果需要浏览多个集合视图,可以将上面的UICollectionView更改为您要查找的子类。更简单的方法是在cellForItemAtIndexPath中为您的单元格提供对collectionView的弱引用;这也适用于您的视图控制器而不是您的collectionView,这可能是您真正想要的引用。它必须很弱,因为collectionView保留了单元格;否则你会创建一个循环。

    class CustomCollectionViewCell: UICollectionViewCell {
        weak var customCollectionViewController: CustomCollectionViewController?

    }

    class CustomCollectionViewController: UICollectionViewController {
        override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: CustomCollectionViewCell.self), for: indexPath) as! CustomCollectionViewCell
            cell.customCollectionViewController = self
            return cell
        }
    }