这是我喜欢如何处理此类情况的个人偏好,但我首先将UITableViewCell 子类化,因为您的表格单元格看起来不像默认的 iOS UITableViewCell。基本上你有一个自定义设置,所以你需要一个自定义类。
从那里你应该在你的头文件中设置你的 4 个IBActions
- (IBAction)touchFirstButton;
- (IBAction)touchSecondButton;
- (IBAction)touchThirdButton;
- (IBAction)touchFourthButton;
您不需要在这些操作中传递发送者,因为您不会在这些方法中使用该对象。正在创建它们以转接呼叫。
之后为你的 UITableViewSubClass 设置一个协议
@protocol UITableViewSubClassDelegate;
记得把它放在@interface声明之前
给您的销售委托财产
@property (nonatomic, strong) id<UITableViewSubClassDelegate> delegate;
最后定义你的实际协议,你需要设置 4 个方法,每个按钮 1 个,并将你的子类作为参数
@protocol UITableViewSubClassDelegate <NSObject>
- (void)forwardedFirstButtonWithCell:(UITableViewSubClass*)cell;
- (void)forwardedSecondButtonWithCell:(UITableViewSubClass*)cell;
- (void)forwardedThirdButtonWithCell:(UITableViewSubClass*)cell;
- (void)forwardedFourthButtonWithCell:(UITableViewSubClass*)cell;
@end
这将被放置在底部的@interface @end 部分之外
然后在你的@interface 和@implementation 中创建一个configureWithModel: 方法以及你的模型的一个属性
@接口:
@property (nonatomic, strong) Model *model;
- (void)configureWithModal:(Model*)model;
@实现:
- (void)configureWithModal:(Model*)model {
self.model = model;
// custom UI set up
}
从这里您应该在@implementation 文件中配置您的操作方法以调用委托方法,我只显示第一个,但您可以使用所有 IBActions 来执行此操作
- (void)configureWithModal:(Model*)model {
[self.delegate forwardFirstButtonWithCell:self];
}
从这里您的自定义单元格设置完成,我们需要返回显示 UITableView 的 UIViewController。首先进入视图控制器的头文件,导入你自定义的 UITableViewCellSubClass,然后设置类来实现这个协议。
它应该看起来像这样
@interface MYViewController : UIViewController <UITableViewSubClassDelegate>
从那里你应该进入你的 cellForRowAtIndexPath: 方法并配置你的自定义 UITableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCellSubClass *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
cell.delegate = self;
Model *cellModel = self.tableData[indexPath.row];
[cell configureWithModel:cellModel];
return cell;
}
现在进入您的单元类并将所有协议方法复制粘贴到您的 viewController 类中。我将展示一个作为示例。
在你的 UIViewController 中:
- (void)forwardedFirstButtonWithCell:(UITableViewSubClass*)cell {
Model *cellModel = cell.model;
// do stuff with model from outside of the cell
}
对所有方法都这样做,你应该会很好。
请记住将所有#imports 放入其中,这样就没有前向声明,并记住将 IBActions 链接到您的故事板或 xib 文件。如果您想为表格单元格自定义 xib,则必须检查单元格是否为 nil,然后分配一个新单元格,但如果您使用的是原型单元格,那么这就足够了。
为简单起见,我提出了FirstButtonWithCell: 但我鼓励将名称命名为描述其正在执行的操作,例如 displayPopOverToEnterData 或类似名称。从那里您甚至可以更改委托协议方法的参数以采用模型而不是
- (void) displayPopOverToEnterDataWithCell:(UITableViewSubClass*)cell;
做起来
- (void) displayPopOverToEnterDataWithModel:(Model*)model;
但是,我不知道您需要从单元格中访问什么类型的信息。因此,请根据需要更新这些方法。