I have a custom UICollectionViewCell with a button inside it. When I tap the button, an event is fired inside that subclass. I want to then trigger an event on the UICollectionView itself, which I can handle in my view controller.
Pseudo-code:
class MyCell : UICollectionViewCell {
@IBAction func myButton_touchUpInside(_ sender: UIButton) {
// Do stuff, then propagate an event to the UICollectionView
Event.fire("cellUpdated")
}
}
class MyViewController : UIViewController {
@IBAction func collectionView_cellUpdated(_ sender: UICollectionView) {
// Update stuff in the view controller
// to reflect changes made in the collection view
}
}
Ideally, the event I define would appear alongside the default action outlets in the Interface Builder, allowing me to then drag it into my view controller code to create the above collectionView_cellUpdated
function, similar to how @IBInspectable
works in exposing custom properties.
Is there any way to implement a pattern like this in native Swift 3? Or if not, any libraries that make it possible?
I don't understand your question completely but from what I got, you can simply use a
closure
to pass theUIButton
tap event back to theUIViewController
.Example:
1. Custom
UICollectionViewCell
2.
MyViewController
Let me know if you face any issues.
Best thing to do is to make a custom protocol for your custom cell class
Make this cell class have this protocol as a peculiar delegate, and to trigger this delegate:
In your controller, you conform it to the delegate, and you apply the delegate to each cell in
cellForItem: atIndexPath
:Best practice is to pass the cell's indexPath parameter in the delegate method inside of
pressedWithInfo
. It saves you the trouble of calculating which cell actually was pressed; hence why i usually add anindexPath
element to each of my UICollectionViewCell subclasses. Better yet, include the index inside the protocol method: