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

标签 ios uitableview delegates swift4

我有 ViewController1ViewController2ViewController1 有一个 TableView 和一个 TableViewCell 更新其 UI 的类。

我想要做的是,当用户点击 ViewController1TableView 中的 TableViewCell 内的 button 时>,然后将转到 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
    }
  }

}

直到此时,当在任何 tableCell 中单击按钮时,我都可以在 ViewController1 中获取 postId

现在的问题是 postIdshowSecondVc() 中,我如何将 postId 传递给 ViewController2 当我执行 segue 时?

最佳答案

店铺 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
    }
}

关于ios - 如何通过 segue Swift 4 将数据从 View Controller 的 UITableViewCell 类传递到另一个 ViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48607308/

相关文章:

ios - iOS是否具有用于访问智能卡的API

ios - 通用框架二进制文件 : Why Build Simulator and Archive Device?

c# - 使用反射将委托(delegate)连接到事件?

c# - 为什么使用 "new DelegateType(Delegate)"?

ios - native iOS 应用程序中的连字符

ios - 计算一个单词在 TableView 行中出现的次数

ios - 如何segue UIImage?

ios - uitableview 中的所有部分标题都在同一个位置

ios - Swift 3 - 如何截取特定 UITableView 行的屏幕截图

c# - 在分配给事件期间是否会复制委托(delegate)?