在 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)
使用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
以控制演示文稿。
归档时间: |
|
查看次数: |
3738 次 |
最近记录: |