Reputation: 725
I followed exactly this tutorial to create a custom delegate.
I create the delegate
protocol UserTableViewDelegate: class {
func helpClicked()
}
Then in class HelpTableViewCell
weak var delegate: UserTableViewDelegate?
@IBAction func helpButtonClicked(_ sender: UIButton) {
delegate?.helpClicked()
}
In class UserTableViewController
I conform to the delegate UserTableViewDelegate
and then
func helpClicked() {
}
However the function never get called. The delegate variable in class HelpTableViewCell
is always nil and delegate?.helpClicked()
has no effect.
Upvotes: 0
Views: 392
Reputation: 125007
The delegate variable in class HelpTableViewCell is always nil and delegate?.helpClicked() has no effect.
That's because you haven't created a delegate at all. A delegate is an object that implements a particular set of delegate methods. You're not creating any such object, at least in the code you've shown.
I create the delegate
No, you've defined a delegate protocol. You haven't instantiated a class that adopts that protocol. The tutorial that you referenced is pretty sloppy in the language that it uses and doesn't really distinguish between the delegate protocol
, i.e. the set of methods that a given kind of delegate is expected to implement, and the delegate itself, i.e. the particular object that provides those methods to the delegator.
In class UserTableViewController I conform to the delegate UserTableViewDelegate and then
That's the right idea, but if the expression delegate?.helpClicked()
doesn't get called because delegate
is nil, then you must have failed to assign the controller as the table's delegate. Sometimes the delegate can be assigned in a storyboard, the same way you'd connect a view controller to its view. You could do that if the table in question uses static cells, where all the cells are created in the storyboard. Just make HelpTableViewCell's delegate
an IBOutlet and then connect it to the UserTableViewController. More often, though, table cells are dynamic and configured at run time; in that case, you'll want to set the delegate
property for your HelpTableViewCell when you configure the cell, most likely in tableView(_:cellForRowAt:)
.
That said, you may not need to bother with delegation at all in the case you've described. A table view's delegate is already informed when the user interacts with a cell. You don't say here whether you're working in iOS or MacOS, but it doesn't matter: both UITableViewDelegate (iOS) and NSTableViewDelegate (macOS) have methods that are called when a cell is tapped or clicked. Cells are usually pretty lightweight objects -- they generally worry mostly about displaying their content properly and leave user interaction to the table's delegate (which is almost always the view controller).
Upvotes: 1
Reputation: 856
Within UserTableViewController
you also need to set the delegate property like below -
nameofyourCustomcellObject.delegate = self
Upvotes: 0