如何确定一个UIButton是否在自定义的UITableViewCell上点击?

下面的实现工作正常,但它不觉得像最优雅的解决scheme。 是否有任何最佳做法或不同的实现来确定UIButton是否在自定义的UITableViewCell上轻敲?

- (IBAction)customCellButtonTapped:(id)sender { UIButton *button = (UIButton *)sender; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0]; NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; // Set the value of the object and save the context } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { TTCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; [self configureCell:cell atIndexPath:indexPath]; [cell.customCellButton addTarget:self action:@selector(customCellButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; [cell.customCellButton setTag:indexPath.row]; return cell; } 

我同意这是不雅的。 由于单元格正在被重用,因此必须更改button标签以保持同步。 更不用说,标签可能是真正的目的所需要的,而不是告诉代码视图在哪一行。

以下是我在包含控件的tableviews中一直使用的方法:

 - (NSIndexPath *)indexPathOfSubview:(UIView *)view { while (view && ![view isKindOfClass:[UITableViewCell self]]) { view = view.superview; } UITableViewCell *cell = (UITableViewCell *)view; return [self.tableView indexPathForCell:cell]; } 

现在,在

 - (IBAction)customCellButtonTapped:(id)sender { NSIndexPath *indexPath = [self indexPathOfSubview:sender]; // use this to access your MOC // or if we need the model item... id myModelItem = self.myModelArray[indexPath.row]; // or if we need the cell UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; 

如果你已经有了一个单元的子类,你可以随时实现一个所有者实现的协议,例如:

自定义单元格

 @protocol TTCustomCellDelegate <NSObject> - (void)customCellWasTapped:(TTCustomCell *)cell withSomeParameter:(id)parameter; @end @interface TTCustomCell : UITableViewCell @property (nonatomic, weak) id<TTCustomCellDelegate> delegate; @end @implementation - (void)buttonWasTapped { if(self.delegate) [self.delegate customCellWasTapped:self withSomeParameter:whateverYouNeed]; } 

视图控制器

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ... cell.delegate = self; ... } - (void)customCellWasTapped:(TTCustomCell *)cell withSomeParameter:(id)parameter { id thing = cell.somePropertyUniqueToThisCell; id otherThing = parameter; }