如何通过segue Swift 4将数据从View Controller的TableViewCell类传递到另一个ViewController?

时间:2018-02-04 10:54:19

标签: ios uitableview delegates swift4

我有ViewController1ViewController2ViewController1TableViewTableViewCell类来更新其用户界面。

我想要做的是,当用户点击button TableViewCell中的TableView内的ViewController1时,会转到ViewController2并且传递数据。

以下是我尝试的内容:

在TableViewCell类

protocol MyDelegate : class {
    func showSecondVc(postId : Int)
}

class MyTableCell : UITableViewCell {

    weak var delegate : RefreshDelegate?

    @IBAction func myButtonTapped(_ sender: Any) {
        self.delegate?.showSecondVc(postId: posts.postId)
    }
}

在ViewController1中:

class ViewController1: UIViewController ,UITableViewDataSource, UITableViewDelegate , MyDelegate {

  func showSecondVc(postId: Int) {
      print("button tapped : \(postId)")
      self.performSegue(withIdentifier: "showSecondVc", sender: self)
  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if segue.identifier == "showSecondVc" {
        //here I want to pass the **postId** to ViewController2
    }
  }

}

在此之前,当postId中的按钮被点击时,ViewController1可以tableCell {/ 1}}。

现在问题是postId位于showSecondVc()内,当我执行segue时如何将postId传递给ViewController2

2 个答案:

答案 0 :(得分:1)

存储postId,以便您可以在prepare(for:sender:)中存储,然后尝试从ViewController2获取segue.destination

private var postId: Int = 0

func showSecondVc(postId: Int) {
    print("button tapped : \(postId)")
    self.postId = postId
    self.performSegue(withIdentifier: "showSecondVc", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showSecondVc",
        let secondVC = segue.destination as? ViewController2 {
        secondVC.postId = self.postId
    }
}

答案 1 :(得分:0)

在ViewController2中声明一个var并将其命名为postID

func showSecondVc(postId: Int) { 
  self.performSegue(withIdentifier: "showSecondVc", sender: postId)
}

并将其设置为准备

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  if segue.identifier == "showSecondVc",
     let secondVC = segue.destination as? ViewController2 {
     secondVC.postID = sender as! Int
 }
}