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 :
@protocol MyProtocol
-(void)customCell:(MyCustomCell*)cell buttonClicked:(id)button;
@end
Property in your cell interface :
@interface MyCustomCell : UITableViewCell ...
...
id<MyProtocol> _delegate;
...
@property (nonatomic, assign) id<MyProtocol> delegate;
...
@end
Synthesize your property with :
@synthesize delegate = _delegate;
Implement the delagate in your controller :
@interface MyCustomContoller : UIViewController<MyProtocol>
Set the delegate when you create your cells (from your controller)
cell.delegate = self
Then from the method called in your cell when the button is clicked :
-(void) buttonClicked:(id)sender {
[self.delegate customCell:self buttonClicked:sender];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With