Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton inside subclassed UITableViewCell needs to call method of parent

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!

like image 526
PengOne Avatar asked Dec 22 '10 14:12

PengOne


1 Answers

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];
}
like image 141
VdesmedT Avatar answered Nov 07 '22 08:11

VdesmedT