子类 UITableViewCell 中的 UIButton 需要调用父类的方法 [英] UIButton inside subclassed UITableViewCell needs to call method of parent

查看:38
本文介绍了子类 UITableViewCell 中的 UIButton 需要调用父类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,如果已经有答案,但我找不到.

Apologies if there answer is already out there, but I could not find it.

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

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).

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

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 没有 nib 文件,全部以编程方式完成.在 CustomTableViewCell.h 我声明:

CustomTableViewCell has no nib file, all done programmatically. In CustomTableViewCell.h I declare:

    UIButton *mybutton;

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

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];

但我想调用父视图中的buttonPressed:"方法.已经破解了几个小时,所以如果有人能原谅我自己的愚蠢,我将不胜感激.谢谢!

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!

推荐答案

那你就用委托模式吧!

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

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 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;

在你的控制器中实现 delagate :

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];
}

这篇关于子类 UITableViewCell 中的 UIButton 需要调用父类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆