我正在研究Apple Developer的教程:Start Developing iOS Apps (Swift),我对push和modal segue感到困惑。
有两种情况,导航栏中的“保存”和“取消”按钮,从场景2支持到场景1。
如果按下取消按钮,它将调用不同的方法来解除场景2:
@IBAction func cancel(_ sender: UIBarButtonItem) {
// Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways.
let isPresentingInAddMealMode = presentingViewController is UINavigationController
if isPresentingInAddMealMode {
dismiss(animated: true, completion: nil)
}
else if let owningNavigationController = navigationController{
owningNavigationController.popViewController(animated: true)
}
else {
fatalError("The MealViewController is not inside a navigation controller.")
}
}
在此方法中,如果场景由模态segue呈现,则调用dismiss(animated:completion :),并且 如果场景由push segue呈现,则调用popViewController(animated :)从导航堆栈中弹出ViewController。
但是对于Save按钮,教程会覆盖场景2中的方法,prepare(for:sender :)和场景1中的action方法unwindToMealList(sender :)。 然后将Save按钮拖动到Exit(场景停靠栏中的按钮)并选择unWindToMealList(sender :)方法。 所以流程将是:prepare(for:sender :) - >场景2被解雇并且场景1被呈现 - > unWindToMealList(发件人:)
我想知道代码片段并没有明确地解除场景2并在按下“保存”按钮时删除导航堆栈中的ViewController。 我知道模态segue不会将ViewController推送到导航堆栈,但push segue会推动它。 为什么代码片段不会从导航堆栈中弹出?
非常感谢。
答案 0 :(得分:1)
您正在阅读的教程似乎正在使用unwind segues。
展开segue,就像普通的segues一样,有一个源和一个目的地,你可以在prepareForSegue
中准备它,但它不会显示目标VC,而是关闭源VC,以便目标VC是所示。
Unwind segues在不同情况下的表现不同。当您使用push segue从VC A呈现VC B,以及从B到A的展开segue时,展开segue将从导航堆栈弹出VC B.当您以模态方式从VC A呈现VC B时,展开segue将忽略模态呈现的VC。
正如您所看到的,展开segues非常聪明。它将自行决定如何显示目标VC。它甚至可以在导航堆栈中弹出两个或更多个VC!