子类UITut中的UIButton需要调用父类的方法

Pen*_*One 8 iphone uibutton uitableview

如果答案已经存在,请道歉,但我找不到.

我有以下设置:MainViewController有一个很大的UITableView和CustomTableViewCell,它是UITableViewCell的子类.CustomTableViewCell的每个实例都在其内容视图中添加了一个UIButton(所有这些都以编程方式完成).

当在给定单元格中按下按钮时,我希望它在MainViewController中调用buttonPressed:方法,更好的是,告诉我包含按下按钮的单元格的indexPath.section.

CustomTableViewCell没有nib文件,都是以编程方式完成的.在CustomTableViewCell.h中,我声明:

    UIButton *mybutton;
Run Code Online (Sandbox Code Playgroud)

虽然我没有保留(没有@property,@synthesize).CustomTableViewCell.m的init方法如下所示:

    myButton = [[UIButton alloc] init];
    [myButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventValueChanged];
    [[self contentView] addSubview:myButton];
    [myButton release];
Run Code Online (Sandbox Code Playgroud)

但我想调用生活在父视图中的"buttonPressed:"方法.一直在偷偷摸摸几个小时,所以如果有人能饶恕我自己的愚蠢,我将不胜感激.谢谢!

Vde*_*edT 16

然后你去代理模式!

定义控制器将遵循的协议以及单元格上的类型id的委托.不要忘记为您使用控制器创建的每个单元分配该委托.

协议 :

@protocol MyProtocol
-(void)customCell:(MyCustomCell*)cell buttonClicked:(id)button;
@end
Run Code Online (Sandbox Code Playgroud)

您的单元格界面中的属性:

@interface MyCustomCell : UITableViewCell ...
...
   id<MyProtocol> _delegate;
...
   @property (nonatomic, assign) id<MyProtocol> delegate;
...
@end
Run Code Online (Sandbox Code Playgroud)

使用以下内容合成您的属性:

@synthesize delegate = _delegate;
Run Code Online (Sandbox Code Playgroud)

在控制器中实现delagate:

@interface MyCustomContoller : UIViewController<MyProtocol>
Run Code Online (Sandbox Code Playgroud)

创建单元格时设置委托(从控制器)

cell.delegate = self
Run Code Online (Sandbox Code Playgroud)

然后从单击按钮时单元格中调用的方法:

-(void) buttonClicked:(id)sender {
[self.delegate customCell:self buttonClicked:sender];
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,因为您在接口之前定义协议,然后在预编译器读取协议定义时,它不知道CustomCell.在接口后定义协议并添加@protocol ResetStatsDelegate; 在界面之前 (2认同)