微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我对编程和 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)
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。