你可以繼承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細胞。
E.g.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ABCTableViewCell *cell = (ABCTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"Cell"];
cell.delegate = tableView;
return cell;
}
你可以繼承UITableView和UITableViewCell,然後爲該按鈕添加一個委託方法。例如tableView:buttonWasPressedForCell:&buttonWasPressedForCell :. tableView將符合單元的委託並接收消息buttonWasPressedForCell :.然後,tableView將發送消息tableView:buttonWasPressedForCell:它是委託,在這種情況下,您的控制器。這樣,您就知道哪個UITableView和哪個UITableViewCell消息是從哪個發送的。 – Jonathan
好問題,真棒:) –