如何使用swift在UIcollectionview单元格中获取焦点单元格的“父级” - tvOS

Sti*_*hof 4 uicollectionview uicollectionviewcell swift tvos

我为我的 tvOS 应用程序制作了某种 Netflix 布局,其中包含多个名为:featuredCollectionViewstandardCollectionView.

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

编码

func pressedThePlayPauseButton() {

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

       let collectionViewOfFocusedCell = ...
Run Code Online (Sandbox Code Playgroud)

Jos*_*ann 5

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

    var parentCollectionView = self.superview
    while parentCollectionView is UICollectionView != true {
        parentCollectionView = parentCollectionView?.superview
    }
Run Code Online (Sandbox Code Playgroud)

如果您需要浏览多个集合视图,您可以将上面的 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
        }
    }
Run Code Online (Sandbox Code Playgroud)