【问题标题】:How to get index path on click of button from UITableView in Swift 5 [duplicate]如何在 Swift 5 中单击 UITableView 中的按钮时获取索引路径 [重复]
【发布时间】:2020-01-25 16:15:15
【问题描述】:

在tableview中,单元格上有按钮,需要获取tableview的索引,意思是点击了哪个索引单元格的按钮。因此,无法在 swift 5 中实现它。到目前为止尝试过的是,但这给了我错误的价值。

let position: CGPoint = sender.convert(CGPoint.zero, to: organizationsTableView)
if let indexPath = organizationsTableView.indexPathForRow(at: position) {
    print(indexPath)
}

【问题讨论】:

  • 一个漂亮的swifty方法是回调闭包。它们比标签或协议或查看几何数学更有效。
  • 请使用我的代码或任何其他更好的方式发布答案

标签: ios iphone ios13 xcode11 swift5


【解决方案1】:

回调闭包是 Swift 中最有效的方法。

但是,如果可以插入、删除或移动单元格,则仅在 Prakash Shaiva 的回答中捕获 cellForRowAt 中的索引路径是不够的。在这种特殊情况下,您必须通过单元格

class MyTableViewCell: UITableViewCell {

    var callback : ((UITableViewCell) -> Void)?

    @IBAction func push(_ sender: UIButton) {
        callback?(self)
    }   
}

并获取闭包中单元格的当前索引路径

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "MyIdentidier", for: indexPath) as! MyTableViewCell
    cell.callback = { currentCell in
        let currentIndexPath = tableView.indexPath(for: currentCell)!
    }
    return cell
}

【讨论】:

    【解决方案2】:

    1) 在您的自定义单元格中添加闭包:

    class YoutuberTableViewCell: UITableViewCell {
    
        var buttonAction : (() -> ())?
    
    
        @IBAction func buttonTapped(_ sender: UIButton) {
    
            buttonAction?()
        }
    
    }
    

    2) 在你的 cellForRowAt 中实现闭包

    extension ViewController : UITableViewDataSource {
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
            let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath) as! YoutuberTableViewCell
    
            cell.buttonAction = { [unowned self] in
                let selectedIndexPath = indexPath.row
            }
    
            return cell
        }
    
    }
    

    【讨论】:

    • 你不需要[unowned self],数据源不拥有单元格,除非你让它成为。
    【解决方案3】:

    将 indexPath.row 作为标签添加到 tableViewCell 内的按钮

    button.tag = indexPath.row
    button.addTarget(self, action: #selector(buttonClickMethod(_:)), for: .touchUpInside)
    

    如果您使用的是 xib,那么您可以从 Attribute Inspector 向按钮添加标签

    在 buttonClickMethod 里面你可以像这样访问索引

    func buttonClickMethod(_ sender: UIButton){
       let index = sender.tag
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-10
      • 2018-11-03
      • 1970-01-01
      • 2019-11-25
      • 2018-11-10
      • 2019-04-02
      • 1970-01-01
      相关资源
      最近更新 更多