如何在 SwiftUI 中显示 UIAlertController?

myu*_*ews 4 swift swiftui

在 UIKit 中,通常会UIAlertController在响应某些操作时呈现模态弹出警报消息。

SwiftUI 中是否有模态警报控制器类型?

有没有办法UIAlertController从 SwiftUI 类中呈现 a ?似乎可以使用UIViewControllerRepresentable但不确定是否需要这样做?

小智 13

这才有效:

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)
}
Run Code Online (Sandbox Code Playgroud)

将其放入 Helper 类中。

用法:

Helper.alertMessage(title: "Test-Title", message: "It works - even in SwiftUI")
Run Code Online (Sandbox Code Playgroud)

  • 从 iOS 15 开始,“rootViewController”已被弃用。如果您使用 SwiftUI,最好更新到它的 `.alert(isPresented:, content:)` 方法 (5认同)

EvZ*_*EvZ 7

使用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")) }
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

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