使用 SwiftUI 在条件内显示警报

Display an Alert inside a conditional with SwiftUI

我知道 Alert 可以表示为 Button 的函数,但是 Alert 可以在条件语句中表示吗?如:

struct ContentView: View {

    var body: some View {
        Text("Hello World!")
    }
}    

if isValid {

    //present alert
    let alert = UIAlertController(title: "My Title", message: "This 
    is my message.", preferredStyle: UIAlertController.Style.alert)

    alert.addAction(UIAlertAction(title: "OK", style: 
    UIAlertAction.Style.default, handler: nil))

    self.present(alert, animated: true, completion: nil)
}

有了这个我得到

Value of type 'ContentView' has no member 'present'

我不确定你为什么要使用 UIKit。这是一个示例,说明当某些内容更改标志时如何显示警报。在这种情况下,一个两秒计时器:

import SwiftUI

class MyModel: ObservableObject {
    @Published var isValid: Bool = false

    init() {
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
            self.isValid = true
        }
    }
}

struct ContentView: View {
    @ObservedObject var model: MyModel = MyModel()

    var body: some View {
        VStack {
            Text("Some text")
            Text("Some text")
            Text("Some text")
            Text("Some text")
        }.alert(isPresented: $model.isValid, content: {
            Alert(title: Text("Title"),
                  message: Text("Message"),
                  dismissButton: .default(Text("OK")) { print("do something") })
        })
    }
}