我有ViewController1
和ViewController2
。ViewController1
有TableView
个TableViewCell
类来更新其用户界面。
我想要做的是,当用户点击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
?
答案 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
}
}