2

This should be simple but I am hoping to display an alert when a condition is true.(see below) I have seen lots where you used a button to trigger an alert, but I just want an alert to trigger when a condition is met such as in a simple "If" statement. Which should appear as soon as the code is loaded.

import SwiftUI

struct ContentView: View {
    @State private var showingAlert = false
    var score = 3

var body: some View {
    VStack{
        if score == 3 {

       showingAlert = true

        } .alert(isPresented: $showingAlert) {
        Alert(title: Text("Hello SwiftUI!"), message: Text("This is some detail message"), dismissButton: .default(Text("OK")))
    }

    }
    }
Jerry
  • 21
  • 2

1 Answers1

0

You can check if your condition is true in the init() method of the view and then set the initial value of your showingAlert.

struct ContentView: View {
    @State private var showingAlert = false
    var score = 3

    init()
    {
        //check if condition is true
        if (true)
        {
            self._showingAlert = State(initialValue: true)
        }
    }

    var body: some View {
        VStack{
            EmptyView()
        } .alert(isPresented: self.$showingAlert) {
            Alert(title: Text("Hello SwiftUI!"), message: Text("This is some detail message"), dismissButton: .default(Text("OK")))
        }

    }
}
davidev
  • 7,694
  • 5
  • 21
  • 56