[英]How do I present a UIAlertController in SwiftUI?
In UIKit, it is common to present UIAlertController
for modal pop up alert messages in response to some action.在 UIKit 中,通常会为响应某些操作的模式弹出警报消息呈现UIAlertController
。
Is there a modal alert controller type in SwiftUI? SwiftUI 中是否有模态警报 controller 类型?
Is there a way to present a UIAlertController
from SwiftUI classes?有没有办法从 SwiftUI 类中呈现UIAlertController
? It seems like this may be possible using UIViewControllerRepresentable
but not sure if that is required?使用UIViewControllerRepresentable
似乎可以做到这一点,但不确定是否需要这样做?
import SwiftUI
struct SwiftUIView: View {
@State private var showAlert = false;
var body: some View {
Button(action: { self.showAlert = true }) {
Text("Show alert")
}.alert(
isPresented: $showAlert,
content: { Alert(title: Text("Hello world")) }
)
}
}
Bind to isPresented
in order to control the presentation.绑定到isPresented
以控制演示。
This just works:这很有效:
class func alertMessage(title: String, message: String) {
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { (action: UIAlertAction) in
}
alertVC.addAction(okAction)
let viewController = UIApplication.shared.windows.first!.rootViewController!
viewController.present(alertVC, animated: true, completion: nil)
}
Put it in a Helper-Class.把它放在一个助手类中。
Usage:用法:
Helper.alertMessage(title: "Test-Title", message: "It works - even in SwiftUI")
You can present UIKit Alert in SwiftUI using notificationCenter您可以使用通知中心在 SwiftUI 中显示 UIKit 警报
At SceneDelegate.swift on "func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)" insert this code {在 SceneDelegate.swift 上的“func 场景(_ 场景:UIScene,willConnectTo session:UISceneSession,选项 connectionOptions:UIScene.ConnectionOptions)”插入此代码 {
NotificationCenter.default.addObserver(self, selector: #selector(self.showAlert), name: Notification.Name("showAlert"), object: nil)
and add this function并添加此 function
@objc private func showAlert(notification: NSNotification){
let msg: String = notification.object as! String
let alert = UIAlertController(title: "Title", message: msg, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "οκ", style: .cancel) { (action) in
}
alert.addAction(cancelAction)
DispatchQueue.main.async {
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}
}
Now you can make the app to appear a message with UIKit AlertController writing this code on an action in a swifui class现在,您可以让应用程序显示一条消息,其中 UIKit AlertController 在 swifui class 中的操作上编写此代码
var body: some View {
Button(action:{
NotificationCenter.default.post(name: Notification.Name("showAlert"), object: "Ελέγξτε το δίκτυο σας και προσπαθήστε αργότερα.")
}
}
I'm using extension of UIViewController to get current vc and UIAlertController to present 'Alert'.我正在使用 UIViewController 的扩展来获取当前的 vc 和 UIAlertController 来呈现“警报”。 Maybe you can try this as followings:也许您可以尝试如下:
extension for UIViewController UIViewController 的扩展
extension UIViewController {
class func getCurrentVC() -> UIViewController? {
var result: UIViewController?
var window = UIApplication.shared.windows.first { $0.isKeyWindow }
if window?.windowLevel != UIWindow.Level.normal {
let windows = UIApplication.shared.windows
for tmpWin in windows {
if tmpWin.windowLevel == UIWindow.Level.normal {
window = tmpWin
break
}
}
}
let fromView = window?.subviews[0]
if let nextRespnder = fromView?.next {
if nextRespnder.isKind(of: UIViewController.self) {
result = nextRespnder as? UIViewController
result?.navigationController?.pushViewController(result!, animated: false)
} else {
result = window?.rootViewController
}
}
return result
}
}
extension for UIAlertController UIAlertController 的扩展
extension UIAlertController {
//Setting our Alert ViewController, presenting it.
func presentAlert() {
ViewController.getCurrentVC()?.present(self, animated: true, completion: nil)
}
func dismissAlert() {
ViewController.getCurrentVC()?.dismiss(animated: true, completion: nil)
}
}
And you can create your showAlert function now您现在可以创建您的 showAlert function
func showMyAlert() {
let myAlert = UIAlertController(title: "Confirm order", message: "Are you sure to order two box of chocolate?", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok!", style: .default) { (_) in
print("You just confirm your order")
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
print(You cancel it already!)
}
myAlert.addAction(okAction)
myAlert.addAction(cancelAction)
myAlert.presentAlert()
}
Wish my answer can help you.希望我的回答能帮到你。 :-) :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.