Josue Garcia
Josue Garcia

Reputation: 33

How do I create an alert which only appears when app is opened with SwiftUI?

I am new to app development and have recently created a game called bullseye.

I would like to display an alert when the app is first opened that gives instructions to the users about the game they are about to play.

I am having trouble creating this alert in swiftUI without a button and would like to know if anyone can help me with this problem.

PS - I am using Xcode 11

Thank you

Upvotes: 3

Views: 1549

Answers (1)

Nerdy Bunz
Nerdy Bunz

Reputation: 7417

I'm not a SwiftUI expert, but this worked for me:

import SwiftUI

struct ContentView: View {

    // In the future, you can use this var to control whether or not to show an alert based on some other condition.
    @State var alertShouldBeShown = true

    var body: some View {
        // attach the alert to the last view in your view hierarchy
        Text("Hello, World!").alert(isPresented: $alertShouldBeShown, content: {

            Alert(title: Text("Alert:"),
                  message: Text("This is the alert. :)"),
                  dismissButton: Alert.Button.default(
                    Text("OK"), action: {

                        //

                  }
                )
            )
        })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Upvotes: 2

Related Questions