如果答案已经存在,但我找不到它,我们深表歉意。
我有以下设置:MainViewController,它有一个大的 UITableView 和 CustomTableViewCell,它是 UITableViewCell 的子类。 CustomTableViewCell 的每个实例都有一个 UIButton 添加到其内容 View 中(全部以编程方式完成)。
当在给定单元格中按下按钮时,我希望它调用 MainViewController 中的 buttonPressed: 方法,更好的是,告诉我包含按下的按钮的单元格的 indexPath.section 。
CustomTableViewCell 没有 nib 文件,全部以编程方式完成。在 CustomTableViewCell.h 中我声明:
UIButton *mybutton;
虽然我不保留(没有@property,@synthesize)它。 CustomTableViewCell.m 的 init 方法如下所示:
myButton = [[UIButton alloc] init];
[myButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventValueChanged];
[[self contentView] addSubview:myButton];
[myButton release];
但我想调用位于父 View 中的“buttonPressed:”方法。我已经为此花了几个小时了,所以如果有人能避免我自己的愚蠢,我将不胜感激。谢谢!
最佳答案
然后你就可以使用委托(delegate)模式了!
定义您的 Controller 将遵循的协议(protocol)以及单元上类型 id 的委托(delegate)。不要忘记为您使用 Controller 创建的每个单元分配该委托(delegate)。
协议(protocol):
@protocol MyProtocol
-(void)customCell:(MyCustomCell*)cell buttonClicked:(id)button;
@end
单元界面中的属性:
@interface MyCustomCell : UITableViewCell ...
...
id<MyProtocol> _delegate;
...
@property (nonatomic, assign) id<MyProtocol> delegate;
...
@end
用以下内容合成您的属性:
@synthesize delegate = _delegate;
在 Controller 中实现延迟:
@interface MyCustomContoller : UIViewController<MyProtocol>
在创建单元格时设置委托(delegate)(从 Controller )
cell.delegate = self
然后从单击按钮时在单元格中调用的方法:
-(void) buttonClicked:(id)sender {
[self.delegate customCell:self buttonClicked:sender];
}
关于iphone - 子类 UITableViewCell 中的 UIButton 需要调用父类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4510071/