开发者

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 开发者_如何学Pythoninit 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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜