ios - 如何通过点击笔尖中的按钮来显示警报?
问题描述
我对编程和 swift 比较陌生,我希望你明白开始有时是困难的。
我已经在 NIB 中集成了一个登录表单,如果输入不正确,我想通过 func 调用警报。但是,只有在视图控制器中才能调用出现和解除警报。但是解决这个问题的最佳方法是什么?
解决方案
方法 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)
}
推荐阅读
- javascript - 错误:无法在框架中显示,因为它将“X-Frame-Options”设置为“拒绝”
- swift - NSException - 笔尖但没有得到 UITableView
- laravel - Laravel 7:为类别创建自定义工厂
- ios - 是否可以在不向层次结构添加空白视图的情况下从另一个 Xib 加载 Xib
- javascript - 无服务器:“errorMessage”:“无法读取未定义的属性 'id'”,
- reactjs - 最好在功能组件中使用 useState 或设置为常量(React Native 应用程序)
- error-handling - 如何重用“结果”?
- python - 使用两个 2D 数组进行数组广播 (Python)
- php - 有没有办法解决空白页php错误?
- c - 将字符串从一个数组移动到另一个数组