簡體   English   中英

如何在 SwiftUI 中顯示 UIAlertController?

[英]How do I present a UIAlertController in SwiftUI?

在 UIKit 中,通常會為響應某些操作的模式彈出警報消息呈現UIAlertController

SwiftUI 中是否有模態警報 controller 類型?

有沒有辦法從 SwiftUI 類中呈現UIAlertController 使用UIViewControllerRepresentable似乎可以做到這一點,但不確定是否需要這樣做?

請改用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以控制演示。

這很有效:

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

您可以使用通知中心在 SwiftUI 中顯示 UIKit 警報

在 SceneDelegate.swift 上的“func 場景(_ 場景:UIScene,willConnectTo session:UISceneSession,選項 connectionOptions:UIScene.ConnectionOptions)”插入此代碼 {

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

並添加此 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)
        }
    }

現在,您可以讓應用程序顯示一條消息,其中 UIKit AlertController 在 swifui class 中的操作上編寫此代碼

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

我正在使用 UIViewController 的擴展來獲取當前的 vc 和 UIAlertController 來呈現“警報”。 也許您可以嘗試如下:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM