我在TableViewController中有一组朋友ID号,我用它来设置每个单元格的标题。在我的子类TableViewCell中,我有一个按钮,用于删除与单元格关联的朋友。我需要知道与单元格关联的朋友ID号,以便在TableViewCell代码中进行HTTP调用。
如何在子类TableViewCell中访问我的Friend ID数组?有没有更好的方法呢?
答案 0 :(得分:1)
听起来你不应该在UITableViewCell中执行那个逻辑,而是在控制器或其他类中完成。
答案 1 :(得分:1)
您应该找到一种方法让单元格向控制器表示已按下按钮并让视图控制器(或者更好的是,视图控制器为业务逻辑创建的对象)。
我最喜欢的方法是在单元格上为要点击的按钮定义一个块属性:
// Custom Cell Header
@property (nonatomic, copy) void(^onButtonTapped)();
@property (nonatomic, strong) NSNumber* friendId;
// Custom Cell Implementation
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.button = [UIButton new];
[self.button
addTarget:self
action:@selector(buttonTapped:)
forControlEvents:UIControlEventTouchUpInside
];
[self.contentView addSubview:self.button];
}
return self;
}
- (void)buttonTapped:(id)sender
{
if (self.onButtonTapped) {
self.onButtonTapped(friendId);
}
}
// Configuring your cell
cell.textLabel.text = @"blah";
cell.friendId = theId;
cell.onButtonTapped = ^(NSNumber *friendId) {
// Do what you want with the friendId
// Most likely ask business logic object to do what it should
// with the friendId
};
最终,您希望将业务逻辑保持在视图之外,最好是在视图控制器之外,因为视图控制器很快就会充满代码和复杂性。
答案 2 :(得分:0)
前段时间我询问了自定义单元格中的UIControl。 Check it here:
我一直在做的是创建一个自定义对象来保存自定义单元格的信息。例如,我有一个带按钮或textField的自定义单元格。在Custom对象上,我为该特定单元格准备了属性。其中一个属性可以是仅链接到该单元格的http地址。另一个属性可以是segueId,它只链接到那个单元格......你明白了。
一开始会让人感到困惑,但它是创建tableViews的有效方法。
我相信它应该适合你的情况。据我所知,策略是跟踪indexPath。