Apologies if there answer is already out there, but I could not find it.
I have the following set-up: MainViewController which has a big UITableView and CustomTableViewCell which is subclass of UITableViewCell. Each instance of CustomTableViewCell has a UIButton added to its content view (all done programmatically).
When the button is pressed in a given cell, I would like for it to call the buttonPressed: method in MainViewController and, even better, tell me the indexPath.section for the cell containing the pressed button.
CustomTableViewCell has no nib file, all done programmatically. In CustomTableViewCell.h I declare:
UIButton *mybutton;
Though I do not retain (no @property, @synthesize) it. The init method for CustomTableViewCell.m reads like this:
myButton = [[UIButton alloc] init];
[myButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventValueChanged];
[[self contentView] addSubview:myButton];
[myButton release];
but I want to call instead the “buttonPressed:” method that lives in the parent view. Been hacking away at this for a few hours, so I’d be grateful if someone could spare me my own stupidity. Thanks!
Then you go with the delegate pattern !
Define a protocol that your controller will respect and a delegate of type id on your cell. Don’t forget to assign that delegate for every cell you create with your controller.
Protocol :
Property in your cell interface :
Synthesize your property with :
Implement the delagate in your controller :
Set the delegate when you create your cells (from your controller)
Then from the method called in your cell when the button is clicked :