【发布时间】:2014-04-11 08:44:21
【问题描述】:
我制作了一个带有按钮的 UITableViewCell 笔尖。按下按钮时,我想删除单元格。表格视图未处于编辑模式,我没有使用标准 UITableViewCell 删除按钮。
我可以从 cellForRowAtIndexPath 将行号存储在按钮标签中,并使用它来确定要删除的行,但是当一个单元格被删除时,按钮标签将不正确。
任何想法如何识别与哪一行相关的按钮按下?
【问题讨论】:
标签: ios uitableview
我制作了一个带有按钮的 UITableViewCell 笔尖。按下按钮时,我想删除单元格。表格视图未处于编辑模式,我没有使用标准 UITableViewCell 删除按钮。
我可以从 cellForRowAtIndexPath 将行号存储在按钮标签中,并使用它来确定要删除的行,但是当一个单元格被删除时,按钮标签将不正确。
任何想法如何识别与哪一行相关的按钮按下?
【问题讨论】:
标签: ios uitableview
喜欢这个answer:
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
【讨论】:
如果您的按钮是单元格内容视图的子视图(应该如此)。您可以使用如下按钮获取单元格的索引路径:
UIView *cellContentView = yourButton.superview;
UITableViewCell *cell = cellContentView.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
然后,只需删除单元格:
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];
【讨论】:
如果按钮调用的方法具有如下签名:
-(void)action:(id)sender;
sender 将是调用该操作的 UIButton:
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = [[button superview] superview];
应该得到你想要的。
【讨论】: