I want to use a delegate to make my cells (from a UICollectionView) communicate with my ViewController.
In my Cell.swift file, I am declaring the protocol needed like this (outside the Cell class):
protocol CellDelegate: class {
func someMethod(param1: String?, param2 param2: Bool)
}
In the same file I am declaring the delegate as follows:
class Cell: UICollectionViewCell {
weak var delegate: CellDelegate?
// ... some code ...
@IBAction func someAction(sender: AnyObject) {
delegate?.someMethod(param1, param2: true)
}
}
Now in my ViewController, I am implementing someMethod
:
extension ViewController: CellDelegate {
func someMethod(param1: String?, param2 param2: Bool) {
// ... some code ...
}
}
Problem : I can not link the protocol with its implementation, cmd + click
in the protocol leads nowhere. In my @IBAction
, someMethod
is not crashing, but it does nothing.
I saw this topic about the subject, but I do not understand where to implement the Step 6.
Can you help me ?
Thank you for your time.
You are missing the final step: populating the
delegate
property of theCell
class. I usually do that incellForRowAtIndexPath
:Note that there is no magic or automated behavior when using delegates:
CellDelegate
protocol)ViewController
class)Cell
class)You just missed the last step, leaving that property uninitialized, so any invocation using optional chaining evaluates to
nil
(like you did in thesomeAction
method), and nothing happens.