gpt4 book ai didi

swift - 为什么 performSegue() 不调用 shouldPerformSegue()

转载 作者:行者123 更新时间:2023-12-01 22:54:56 24 4
gpt4 key购买 nike

对 Swift 编程和一般的移动开发还很陌生。我正在尝试使用 performSegue() 并在没有 if-else 语句的情况下控制它。我在谷歌上搜索了如何使用 override func shouldPerformSegue() 并尝试以不同的方式实现它,但没有一个解决了我的情况。如果开关打开,我需要使用相应的按钮切换到黄色或绿色 View 。即使我让 return false,函数也不会取消 segue 的发生。这种行为的原因是什么,我该如何解决?非常感谢。

class ViewController: UIViewController {

@IBOutlet var segueSwitch: UISwitch!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}

@IBAction func yellowButtonTapped(_ button: UIButton) {
performSegue(withIdentifier: "Yellow", sender: nil)
}

@IBAction func greenButtonTapped(_ button: UIButton) {
performSegue(withIdentifier: "Green", sender: nil)
}

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// return segueSwitch.isOn
return false
}

}

storyboard

最佳答案

如果您在代码中使用 performSegue(withIdentifier:

shouldPerformSegue 不会被调用。只有当从 Storyboard 中触发 segue 时才会调用此函数。

您可以通过将 2 个按钮添加到 Storyboard中的 ViewController 来轻松测试这一点,一个带有 Storyboard segue,另一个带有 IBOutlet 到新的 ViewController。然后将 print 语句添加到 shouldPerformSegue。在 Button 导出调用 performSegue。只有从 Storyboard执行 segue 的第一个按钮才会打印到控制台。

此外,您不需要它。您将在 shouldPerformSegue 中执行的任何验证都可以在 ...ButtonTapped 函数中完成:

@IBAction func yellowButtonTapped(_ button: UIButton) {
if validateSegue(){
performSegue(withIdentifier: "Yellow", sender: nil)
}
}

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
validateSegue()
}

func validateSegue() -> Bool{
......
}

关于swift - 为什么 performSegue() 不调用 shouldPerformSegue(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73494430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com