我想设置一个在viewControllers之间传递信息的设置,如下所示:1-> 2-> 3-> 2。目前我有一个从VC传递信息的设置
1→2。传递的信息是从表中选择单元格的indexPath。需要传递信息,因为第二个viewController中的代码' viewDidLoad()
取决于所选的单元格。它设置如下(并且工作正常):
VC 1:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "cellSelected" else {return}
let indexPath = self.tableView.indexPathForSelectedRow
let rowSelectedd = indexPath
let destViewController: MainPageCellSelectedViewController = segue.destination as! MainPageCellSelectedViewController
destViewController.rowSelected = rowSelectedd!
}
var rowSelectedd = IndexPath()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "cellSelected", sender: rowSelectedd)
}
VC 2(使用传递的信息): var rowSelected = IndexPath()//这有从MainPageVC准备的信息
override func viewDidLoad() {
super.viewDidLoad()
if rowSelected.section == 0{
//do something
} else{
// do something else
}
}
在第二个viewController中有一个按钮,它可以分割到第三个viewController(这也可以正常工作)。但是,在那个第三个 viewController中有一个后退按钮,它会回到第二个viewController。问题是,第二个viewController的viewDidLoad()
代码取决于从第一个VC传递的变量。由于它没有被传递(因为segue现在是从3> 2而不是1> 2),应用程序崩溃了。我不确定什么是适当传递此信息的最佳方式。应该怎么做?
答案 0 :(得分:1)
除非你使用Unwind segue,否则你不会真正使用segues向后导航。从你所描述的,听起来像委托是你想要的。
尝试这样的事情:
protocol ThirdVCDelegate {
func somethingHappens()
}
class SecondVC: UIViewController {
override func prepare(for segue:UIStoryboardSegue,
sender: Any?)
{
if segue.identifier == "whatever the segue is between second and third VC" {
let thirdVC = segue.destination as! ThirdVC
thirdVC.delegate = self
}
}
}
extension SecondVC: ThirdVCDelegate {
func somethingHappens() {
// Do whatever you want in SecondVC in response to some action in ThirdVC
}
}
class ThirdVC: UIViewController {
var delegate:ThirdVCDelegate!
func someMethodWhereYouWantToMakeACallbacktoSecondVC {
delegate.somethingHappens()
// You can pop or dismiss your thirdVC if you're done with it here.
}
}
如果要将特定值从thirdVC传递到secondVC,还可以向协议方法添加参数。