How present a view from a nib cell

50 views Asked by At

I have a collection view, and register cell with UINib, but it seems can't present a viewcontroller inside the UINib cell.

I want present a viewController, but the code inside the nib cell 'self.present(.....)' is not working.

How present a view from a ceollectionView nib cell?

1

There are 1 answers

0
jrturton On

present is a method on a view controller, not a view. If you want to present another view controller, you'll need to let the current view controller know about it. In UIKit this is often done via the delegate pattern.

You will need to create your own delegate protocol and implement it in the view controller.

protocol MyDelegate: AnyObject {
    func presentSomething(from cell: MyCell)
}
extension MyViewController: MyDelegate {
    func presentSomething(from cell: MyCell) {
        present(....
    }
}

And add a delegate property to the cell:

class MyCell: UICollectionViewCell {
    weak var delegate: MyDelegate?
}

Collection view data sources are commonly the view controller that hosts the collection view. When you are configuring the collection view cell, you can set the delegate of the cell at this point:

... your existing cell configuration ...
cell.delegate = self
return cell

This assumes you want to present something on the parent view controller in response to a particular action on the cell that is not selection.

If you're selecting the cell, then just use the didSelect collection view delegate method.

If you want to add a child view controller that is going to live inside the collection view cell, then that's a slightly different (and more fraught with danger, because of cell reuse) approach which you may want to rethink.