访问 UICollectionView 的父 UIViewController

Access a UICollectionView's parent UIViewController

我的问题很简单。我有一个包含 UICollectionView 的 UIViewController。在初始化我的单元格时,我为每个单元格添加了一个手势识别器,这样当你点击并按住它时,它会调用一个带有选择器的函数。

此函数随后创建了一个我想要呈现的 UIAlertController。 (基本上,你持有一个单元格,它会询问你是否要删除它,如果你说是,它会从 CollectionView 中删除它)

问题是我无法从我的 UICollectionView 显示 UIAlertController,因为它不是 ViewController。

我想以编程方式获取包含 UICollectionView 的 UIViewController,以通过 UICollectionView 实现中的函数显示此警报。

我通过在我的自定义 UICollectionViewCell 中制定协议并将这些事件委托回 UIViewController 来做到这一点,就像这样

在你的MyCollectionViewCell

protocol MyCollectionViewCellDelegate: class {
    func didLongPressCell()
}

class MyCollectionViewCell:UICollectionViewCell {

    weak var delegate:MyCollectionViewCellDelegate?

    func longPressAction() {
        if let del = self.delegate {
            del.didLongPressCell
        }
    }

}

然后回到你的MyViewController

class MyViewController:UIViewController, MyCollectionViewCellDelegate {

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyCollectionViewCell
        cell.delegate = self
        return cell
    }

    func didLongPressCell() {
        // do what you want with the event from the cell here
    }

}

要记住的重要一点是为每个单元格设置委托

cell.delegate = self

并在要接收事件的视图控制器中采用新协议

class MyViewController:UIViewController, MyCollectionViewCellDelegate

我没有测试过这段代码,我不确定在像这样的每个单元格中存储对 viewController 的引用的最佳实践,但我做了一些非常相似的事情,让我知道你过得怎么样。


编辑: 如果您已将 UICollectionView 子类化,则将其传递给视图控制器,以便您可以像这样使用它。

您的 MyViewController 现在看起来像这样

class MyViewController:UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let collectionView = MyCollectionView()
        collectionView.viewController = self
        self.view.addSubview(collectionView)
    }

}

以及您的自定义 collection 视图 MyCollectionView

class MyCollectionView:UICollectionView, MyCollectionViewCellDelegate {

    weak var viewController:UIViewController?

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyCollectionViewCell
        cell.delegate = self
        return cell
    }

    func didLongPressCell() {
        if let vc = self.viewController {
            // make use of the reference to the view controller here
        }
    }

}

UICollectionViewCell和之前一样