如何在SwiftUI中呈现UIAlertController?

xqnpmsa8  于 2024-01-05  发布在  Swift
关注(0)|答案(4)|浏览(128)

在UIKit中,通常会为响应某些操作的模态弹出警报消息呈现UIAlertController
SwiftUI中是否有模态警报控制器类型?
有没有一种方法可以从SwiftUI类中呈现UIAlertController?似乎可以使用UIViewControllerRepresentable,但不确定是否需要?

qcbq4gxm

qcbq4gxm1#

这只是工作:

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)
}

字符串
把它放在一个助手类。
使用方法:

Helper.alertMessage(title: "Test-Title", message: "It works - even in SwiftUI")

9jyewag0

9jyewag02#

使用Alert代替。

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")) }
        )
    }
}

字符串
绑定到isPresented以控制演示文稿。

更新:

正如James Toomey在评论中提到的,有一个更好的方法:alert(_:isPresented:presenting:actions:message:)
官方文档:https://developer.apple.com/documentation/swiftui/view/alert(_:ispresented:presenting:actions:message:)-8584l

eni9jsuy

eni9jsuy3#

我正在使用UIViewController的扩展来获取当前的vc和UIAlertController来呈现'Alert'。也许你可以尝试如下:
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
    }
}

字符串
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)
    }
}


现在您可以创建showAlert函数了

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()
}


希望我的回答能帮到你:-)

zf2sa74q

zf2sa74q4#

您可以使用notificationCenter在SwiftUI中呈现UIKit警报
在SceneDelegate.swift on“func scene(_ scene:UIScene,willConnectTo session:UISceneSession,options connectionOptions:UIScene.ConnectionOptions)”插入以下代码{

NotificationCenter.default.addObserver(self, selector: #selector(self.showAlert), name: Notification.Name("showAlert"), object: nil)

字符串
并添加此功能

@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)
        }
    }


现在,您可以使用UIKit AlertController在swifui类中的操作上编写此代码,使应用程序显示消息

var body: some View {
        Button(action:{
               NotificationCenter.default.post(name: Notification.Name("showAlert"), object: "Ελέγξτε το δίκτυο σας και προσπαθήστε αργότερα.")
 }
}

相关问题