【问题标题】: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 中需要它

【问题讨论】:

  • 请看question which already answered yours,虽然很多都在ObjC中,但它们实际上可以很容易地转换为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)
    }

【讨论】:

  • 你能告诉我btn是什么吗?
  • 这是你的 UIButton。
  • 应该是行动还是出口?
  • 所以用 btnTapped 替换 btn。
  • 是的,它有效)谢谢老兄
【解决方案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 等。

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    相关资源
    最近更新 更多