ios - 准备 segue 无法按预期工作

标签 ios swift swift3 segue

我想使用 performSegue 移动到另一个 View ,如下所示

self.performSegue(withIdentifier: "successRegistration", sender: nil)

我想在我的目标 View 中显示警报,因此我重写了准备功能,如下所示

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "successRegistration" {
            loginModel.alert(fromController: self)
            print("working")
        }
    }

但准备功能似乎不起作用,因为 working 未打印到控制台

我尝试删除我的 prepare 函数并更改我的 performSegue 如下

self.performSegue(withIdentifier: "successRegistration", sender: self.loginModel.alert(fromController: self))

上面的行确实打印了警报,但它没有将我带到另一个 View 。

如何在转至其他 View 后显示警报?

最佳答案

在准备过程中在目标 View Controller 上显示警报将导致:

"Attempt to present UIAlertController on SecondViewController whose view is not in the window hierarchy!"

要实现您想要的效果,您只需在第二个 View Controller 类中添加一个变量并将其默认为 false

//In your second view controller
var shouldPresentAlertOnOpen: Bool = false

然后您可以添加逻辑以在该 View Controller 的 viewWillAppear 方法中显示警报,如下所示:

//Still in your second view controller
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if shouldPresentAlertOnOpen {
        //Present your alert here
        let alert = UIAlertController(title: "My Alert", message: "My awesome message", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
}

现在回到您的第一个 View Controller ,您可以将准备方法更新为:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "successRegistration" {
        let destinationVC = segue.destination as! SecondViewController
        destinationVC.shouldPresentAlertOnOpen = true
    }
}

请注意,SecondViewController 应更新为您的第二个 View Controller 类。

我很确定还有其他方法可以做到这一点,这只是我的方法。

关于ios - 准备 segue 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43758928/

相关文章:

ios - 如何将 jpg 文件添加到 ipa 并使用 FileStream 类加载它们

ios - Flutter Http 请求未在 iOS 上执行

ios - 从 AppDelegate 调用委托(delegate)函数不起作用

ios - 访问 Assets.xcassets 中的所有图像 ?? [ swift 3 ]

ios - 对 NSMutableArray 进行排序

ios - 如何从 Swift 中的 UIAlertController 中删除 UIAlertAction?

swift - 更改 TextView 中字符串数组的样式 - swift - 编辑

swift - 有没有办法将变量/ bool 值传递到 View 的 super View 中?

ios - Xcode swift在多个 Storyboard中管理多个 View Controller

swift - 为什么当我收到远程通知时,我的本地通知没有发送?