Access a UICollectionView's parent UIViewController

你离开我真会死。 提交于 2019-11-30 14:04:04

I do this by making a protocol in my custom UICollectionViewCell and delegate these events back to the UIViewController, something like this

In your MyCollectionViewCell

protocol MyCollectionViewCellDelegate: class {
    func didLongPressCell()
}

class MyCollectionViewCell:UICollectionViewCell {

    weak var delegate:MyCollectionViewCellDelegate?

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

}

Then back in your 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
    }

}

The important bits to remember are to set the delegate for each cell

cell.delegate = self

And adopt your new protocol in the view controller that you want to receive the events in

class MyViewController:UIViewController, MyCollectionViewCellDelegate

I have not tested this code and I'm not sure on best practice of storing references to the viewController in every cell like this, but i do something very similar, let me know how you get on.


Edit: if you have subclassed your UICollectionView then pass it a reference to the view controller so that you can use it like so.

Your MyViewController would now look like this

class MyViewController:UIViewController {

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

}

And your custom collection view 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
        }
    }

}

The UICollectionViewCell would be the same as before

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!