【问题标题】:How do you get the indexPath.section and indexPath.row when a button in a cell is tapped? [duplicate]当点击单元格中的按钮时,如何获取 indexPath.section 和 indexPath.row? [复制]
【发布时间】:2017-09-28 16:25:00
【问题描述】:

我有一个分节的表格视图,当我点击单元格中的按钮时,我必须打印行数和节数。我怎样才能得到这个?

【问题讨论】:

  • @vadian,作为我理解的问题,它不是关于检测单元格中的按钮,而是关于从该单元格获取行和部分您可以在另外提供的链接 vadian 中使用该闭包您可以将 indexpath 作为闭包的参数传递
  • 链接的问题描述了一种在点击单元格中的按钮时获取 indexPath.section 和 indexPath.row 的方法

标签: uitableview swift3


【解决方案1】:

indexPath 存储在您的单元格中,并在按下按钮时检索它。

表格视图控制器

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "custom") as! CustomTableCell
    cell.indexPath = indexPath

    return cell
}

自定义表格单元格

class CustomTableCell: UITableViewCell {
    var indexPath: IndexPath!

    @IBAction func buttonPressed() {
        print(indexPath)
    }
}

【讨论】:

  • 当索引路径传入tableView:didSelectCellAtIndexPath委托方法时,不需要将索引路径存储到自定义tableview单元格中。
  • 请记住,OP 想要在按下 按钮 时检索indexPath,而不是单元格本身。
  • 啊,我误读了这个问题。仍然没有必要创建自定义单元格。按下按钮时,使用按钮的超级视图属性获取 tableview 单元格。然后使用tableview的indexPathForCell方法获取索引路径。
【解决方案2】:

实现 tableView:didSelectRowAtIndexPath: 方法。当它被调用时,一个 NSIndexPath 将被传入,其中包含 section 和 row 属性。

每次按下表格视图单元格时都会调用此方法。索引路径将是被按下的单元格的索引路径。

https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614877-tableview

编辑:

我误读了这个问题。按下按钮时,通过访问按钮的父视图从按钮中获取 TableViewCell。然后使用TableView的indexPathForCell方法获取按钮的indexPath。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 2014-10-25
    • 2016-12-20
    • 2018-01-25
    相关资源
    最近更新 更多