首页 > 解决方案 > 如何通过点击笔尖中的按钮来显示警报?

问题描述

我对编程和 swift 比较陌生,我希望你明白开始有时是困难的。

我已经在 NIB 中集成了一个登录表单,如果输入不正确,我想通过 func 调用警报。但是,只有在视图控制器中才能调用出现和解除警报。但是解决这个问题的最佳方法是什么?

标签: iosswiftalertnib

解决方案


方法 1:您可以传递 ViewController 的弱引用,将这个 nib 作为子视图添加到该引用中,并使用它来显示警报

方法 2:使用协议/委托或闭包在 nib 的视图类和视图控制器之间进行通信,并使用委托方法或闭包呈现警报

方法 3:如果您不想这样做,您可以随时访问根视图控制器并尝试使用根视图控制器呈现警报

如果你正在使用SceneDelegate那么

if let scene = UIApplication.shared.connectedScenes.first, let sceneDelegate = scene.delegate as? SceneDelegate, let window = sceneDelegate.window, let rootViewController = window.rootViewController {
            let alert = UIAlertController(title: "your title", message: "your message", preferredStyle: .alert)
            rootViewController.present(alert, animated: true, completion: nil)
        }

如果你不使用SceneDelegate

        if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
            let alert = UIAlertController(title: "abcd", message: "efgh", preferredStyle: .alert)
            rootViewController.present(alert, animated: true, completion: nil)
        }

推荐阅读