如何告诉我的准备方法按下按钮的单元格?

时间:2018-01-12 16:04:38

标签: ios swift uitableview swift4

我在自定义@IBOutlet weak var cellButton: UIButton!课程中添加了一个按钮tableViewCell,并在我的tableView控制器中添加了一个按钮操作

 @IBAction func cellButtonTap(_ sender: UIButton) {

      performSegue(withIdentifier: "goToMap" , sender: self)

    }

我需要做的是将数据传递给另一个viewController但重要的是要知道按钮被按下的是哪个单元格,所以如何告诉我的方法准备

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "goToMap"...//HERE I DON'T KNOW HOW TO DO

}

按下按钮的单元格?我是初学者,我一直在寻找解决方案两天,但我还没有找到它

2 个答案:

答案 0 :(得分:1)

你可以通过“回拨”关闭来实现......

class MyTableViewCell: UITableViewCell {

    var didButtonTapAction : (()->())?

    @IBAction func cellButtonTap(_ sender: UIButton) {
        // call back closure
        didButtonTapAction()?
    }

}

在表视图控制器中,添加一个类级变量:

var tappedIndexPath: IndexPath?

然后您的表格视图单元格设置变为:

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyTableViewCell

    // set labels, colors, etc in your cell

    // set a "call back" closure
    cell.didButtonTapAction = {
        () in
        print("Button was tapped in cell at:", indexPath)

        // you now have the indexPath of the cell containing the
        // button that was tapped, so
        // call performSegue() or do something else...

        self.tappedIndexPath = indexPath
        performSegue(withIdentifier: "goToMap" , sender: self)
    }

    return cell
}

并准备好了:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "goToMap" {
         // do what you need based on the row / section
         // of the cell that had the button that was tapped, such as:

        if let vc = segue.destination as? MyMapViewController {
              vc.myData = self.dataArray[self.tappedIndexPath.row]
        }

    }

}

答案 1 :(得分:0)

  1. 您确定需要一个按钮吗?通常它是通过表视图选择委托发生的。

  2. 如果您需要一个按钮,则需要提供一种方法来识别按下了哪个按钮。如果您要提供简单的一维项目数组,最简单的方法是设置按钮tag以索引

  3. 像:

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "<id>", for: indexPath) as? Cell else { return UITableViewCell() }
            cell.button.tag = indexPath.row
            //...
            return cell
        }
    

    然后最好用按钮作为发送者触发segue:

     @IBAction func cellButtonTap(_ sender: UIButton) {
          performSegue(withIdentifier: "goToMap" , sender: sender)
     }
    

    你可以获得数据:

     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "goToMap", let index = (sender as? UIView)?.tag {
    
            }
    
    }