您可以继承 UITableView 和 UITableViewCell。然后,为按钮添加委托方法。例如tableView:buttonWasPressedForCell: & buttonWasPressedForCell:。 tableView 将符合单元格的委托并接收消息buttonWasPressedForCell:。然后,tableView 会将消息tableView:buttonWasPressedForCell: 发送给它的委托,在这种情况下,就是你的控制器。这样您就可以知道邮件是从哪个UITableView 和哪个UITableViewCell 发送的。
示例:
ABCTableView.h
@protocol ABCTableViewDelegate <NSObject, UITableViewDelegate>
// You may not need this delegate method in a different UIViewController.
// So, lets set it to optional.
@optional
// Instead of passing the cell you could pass the index path.
- (void)tableView:(ABCTableView *)tableView buttonWasPressedForCell:(ABCTableViewCell *)cell;
@end
@interface ABCTableView : UITableView
// Declare the delegate as an IBOutlet to enable use with IB.
@property (weak, nonatomic) IBOutlet id<ABCTableViewDelegate> delegate;
@end
ABCTableView.m
@implementation ABCTableView
@dynamic delegate;
- (void)buttonWasPressedForCell:(ABCTableViewCell *)cell
{
// Check if the delegate responds to the selector since
// the method is optional.
if ([self.delegate respondsToSelector:@selector(tableView:buttonWasPressedForCell:)])
{
[self.delegate tableView:self buttonWasPressedForCell:cell];
}
}
@end
ABCTableViewCell.h
@protocol ABCTableViewCellDelegate;
@interface ABCTableViewCell : UITableViewCell
// Declare the delegate as an IBOutlet to enable use with IB.
@property (weak, nonatomic) IBOutlet id<ABCTableViewCellDelegate> delegate;
@end
@protocol ABCTableViewCellDelegate <NSObject>
// You may not need this delegate method in a different custom UITableView.
// So, lets set it to optional.
@optional
- (void)buttonWasPressedForCell:(ABCTableViewCell *)cell;
@end
ABCTableViewCell.m
@implementation ABCTableViewCell
- (IBAction)action:(id)sender
{
// Check if the delegate responds to the selector since
// the method is optional.
if ([self.delegate respondsToSelector:@selector(buttonWasPressedForCell:)])
{
[self.delegate buttonWasPressedForCell:self];
}
}
@end
注意:
当您将 tableView:cellForRowAtIndexPath: 中的单元格出列或使用 Interface Builder 添加单元格时,请务必将单元格的委托设置为 tableView。
例如
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ABCTableViewCell *cell = (ABCTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"Cell"];
cell.delegate = tableView;
return cell;
}