简体   繁体   中英

SwiftUI: How can I display an alert on the very first start

I'm new in SwiftUI and I would like to show an alert when the user start the app for the first time. If the user opens the app a second (or third...) time, the alert should not come anymore.

struct ContentView: View {

    @State var alertShouldBeShown = true   
    
    var body: some View {
        VStack {
            Text("Hello World!")
            
            .alert(isPresented: $alertShouldBeShown, content: {

                Alert(title: Text("Headline"),
                      message: Text("Placeholder"),
                      dismissButton: Alert.Button.default(
                        Text("Accept"), action: {
                      }
                    )
                )
            })
        }
    }
}

Update: Xcode 13.4

Original variant is still valid and works "as-is", but now we can simplify code a bit with AppStorage

struct ContentView: View {
    @AppStorage("FirstStart") var alertShouldBeShown = true

    // ... same code

      dismissButton: Alert.Button.default(
        Text("Accept"), action: {
           alertShouldBeShown = false
      })

}

Original

Use UserDefaults to store state value.

Here is possible solution. Tested with Xcode 11.7/iOS 13.7

struct ContentView: View {

    @State var alertShouldBeShown = !UserDefaults.standard.bool(forKey: "FirstStart")

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

            .alert(isPresented: $alertShouldBeShown, content: {

                Alert(title: Text("Headline"),
                      message: Text("Placeholder"),
                      dismissButton: Alert.Button.default(
                        Text("Accept"), action: {
                            UserDefaults.standard.set(true, forKey: "FirstStart")
                      }
                    )
                )
            })
        }
    }
}

import SwiftUI

struct ContentView: View {
    @State private var isAlert = false

    var body: some View {
            Button(action: {
                self.isAlert = true
            }) {
                Text("Click Alert")
                .foregroundColor(Color.white)
            }
            .padding()
            .background(Color.blue)
            .alert(isPresented: $isAlert) { () -> Alert in
                Alert(title: Text("iOSDevCenters"), message: Text("This Tutorial for SwiftUI Alert."), primaryButton: .default(Text("Okay"), action: {
                    print("Okay Click")
                }), secondaryButton: .default(Text("Dismiss")))
        }

    }
}

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

在此处输入图像描述

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