如何防止导航到 UIViewController 检查条件?
How to prevent navigation to UIViewController checking a condition?
我有一个显示视图控制器 (ViewControllerIncluirItem) 的按钮。但是,我需要在导航之前检查一个条件,我尝试在 func override func prepare(for segue: UIStoryboardSegue, sender: Any?)
中检查这个。但是,导航以任何方式发生。我试过这个:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SegueToVcIncluirItem" {
if pricelist != nil {
print("pricelist ok")
} else {
print("selecione pricelist")
return // Here I want prevent.
}
let nav = segue.destination as! UINavigationController
let childVc = nav.topViewController as! ViewControllerIncluirItem
childVc.strTeste = "testado com sucesso"
}
}
您可以在方法shouldPerformSegue(withIdentifier:sender:)
中查看您的情况
您的代码应如下所示:
func shouldPerformSegue(withIdentifier identifier: String,
sender: Any?) -> Bool{
if identifier == "SegueToVcIncluirItem" {
return pricelist != nil
}
return true
}
func prepare(for segue: UIStoryboardSegue, sender: Any?)
在您要求调用时被调用。您必须使用这个:
self.performSegue(withIdentifier: "", sender: nil)
您要输入的条件 func prepare(for segue: UIStoryboardSegue, sender: Any?)
,您应该在调用之前输入。所以应该是:
if pricelist != nil {
print("pricelist ok")
self.performSegue(withIdentifier: "", sender: nil)
} else {
print("selecione pricelist")
}
现在您的 prepare 函数应该看起来非常简单:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let nav = segue.destination as! UINavigationController
let childVc = nav.topViewController as! ViewControllerIncluirItem
childVc.strTeste = "testado com sucesso"
}
我有一个显示视图控制器 (ViewControllerIncluirItem) 的按钮。但是,我需要在导航之前检查一个条件,我尝试在 func override func prepare(for segue: UIStoryboardSegue, sender: Any?)
中检查这个。但是,导航以任何方式发生。我试过这个:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SegueToVcIncluirItem" {
if pricelist != nil {
print("pricelist ok")
} else {
print("selecione pricelist")
return // Here I want prevent.
}
let nav = segue.destination as! UINavigationController
let childVc = nav.topViewController as! ViewControllerIncluirItem
childVc.strTeste = "testado com sucesso"
}
}
您可以在方法shouldPerformSegue(withIdentifier:sender:)
中查看您的情况您的代码应如下所示:
func shouldPerformSegue(withIdentifier identifier: String,
sender: Any?) -> Bool{
if identifier == "SegueToVcIncluirItem" {
return pricelist != nil
}
return true
}
func prepare(for segue: UIStoryboardSegue, sender: Any?)
在您要求调用时被调用。您必须使用这个:
self.performSegue(withIdentifier: "", sender: nil)
您要输入的条件 func prepare(for segue: UIStoryboardSegue, sender: Any?)
,您应该在调用之前输入。所以应该是:
if pricelist != nil {
print("pricelist ok")
self.performSegue(withIdentifier: "", sender: nil)
} else {
print("selecione pricelist")
}
现在您的 prepare 函数应该看起来非常简单:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let nav = segue.destination as! UINavigationController
let childVc = nav.topViewController as! ViewControllerIncluirItem
childVc.strTeste = "testado com sucesso"
}