SwiftUI:如何在第一次启动时显示警报

lul*_*a08 1 xcode swift swiftui

我是 SwiftUI 的新手,我想在用户第一次启动应用程序时显示警报。如果用户第二次(或第三次...)打开应用程序,则不应再出现警报。

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: {
                      }
                    )
                )
            })
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 5

更新:Xcode 13.4

原始变体仍然有效并且“按原样”工作,但现在我们可以使用以下命令稍微简化代码AppStorage

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

    // ... same code

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

}
Run Code Online (Sandbox Code Playgroud)

原来的

用于UserDefaults存储状态值。

这是可能的解决方案。使用 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")
                      }
                    )
                )
            })
        }
    }
}
Run Code Online (Sandbox Code Playgroud)