【问题标题】:How to know the indexPath of the cell SWIFT [duplicate]如何知道单元格 SWIFT 的 indexPath [重复]
【发布时间】:2017-12-29 20:36:51
【问题描述】:
我有一个自定义tableview。它包含一个button。问题是如何知道点击了哪个按钮?来自indexPath.row。我尝试在 didSelectRowAt 中执行此操作,但是我没有选择任何单元格,我只是按button。我在 SWIFT 中需要它
【问题讨论】:
标签:
swift
uibutton
tableview
cell
【解决方案1】:
下面的代码将为您提供 Button 标签,并知道点击了哪个按钮。在 cellForRowAtIndexPath UITableView DataSource Delegate Method 中右键此代码。
cell.btn.tag = indexPath.row
cell.btn.addTarget(self, action: #selector(btnTapped(_:)), for: .touchUpInside)
func btnTapped(_ sender : UIButton) {
print(sender.tag)
}
【解决方案2】:
UIButton * btn = /* your button */;
UITableViewCell * cellContainingBtn = (UITableViewCell*)[btn superview];
UITableView * tbl = (UITableView *)[cellContainingBtn superview];
NSIndexPath * cellIndexPath = [tbl indexPathForCell:cellContainingBtn];
NSInteger index = [cellIndexPath row];
在这里回答:
Get row index of custom cell in UITableview
作为一种简单的替代方法,您可以将单元格的 indexPath.row 分配给按钮的 accessibilityLabel 或 accessibilityHint 等。