这是一个老问题,但我也想回答我的老问题......是的,有一个更简单的方法使用块:
首先,在你的 UITableViewCell 接口中声明一个公共方法:
@interface YourCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIButton *button;
- (void)setDidTapButtonBlock:(void (^)(id sender))didTapButtonBlock;
@end
在 UITableViewCell 子类实现文件中声明一个带有复制属性的私有属性。
#import "YourCell.h"
@interface YourCell ()
@property (copy, nonatomic) void (^buttonTappedBlock)(id sender);
@end
在UITableViewCell构造函数中添加UIControl的target和action,并实现selector方法
- (void)awakeFromNib {
[super awakeFromNib];
[self.button addTarget:self
action:@selector(didTapButton:)
forControlEvents:UIControlEventTouchUpInside];
}
- (void)didTapButton:(id)sender {
if (buttonTappedBlock) {
buttonTappedBlock(sender);
}
}
最后在控制器中实现tableView:cellForRowAtIndexPath:方法中的block代码
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
YourCell *cell = (YourCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
[cell buttonTappedBlock:^(id sender) {
NSLog(@"%@", item[@"title"]);
}];
return cell;
}
更多区块信息,可以阅读Working With Blocks