如何通过点击笔尖中的按钮来显示警报?

问题描述

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

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

解决方法

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

方法 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",completion: nil)
        }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...