简体   繁体   中英

Display an Alert inside a conditional with SwiftUI

I understand that an Alert can be presented as a function of a Button , but can an Alert be presented inside a conditional? Such as:

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

With this I get

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

I'm not sure why are you using UIKit. Here's an example of how an alert may be presented when something changes a flag. In this case, a two second timer:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM