首页 > 解决方案 > SwiftUI - 显示警报

问题描述

我希望在用户无需任何操作而快速移动到新页面时显示警报,我使用 NavigationLink

内容视图.swift

struct ContentView: View {
    var body: some View {
        VStack{
            NavigationLink(destination: SecondView()){
                Text("Go to second view")
            }
        }
    }
}

SecondView.swift

struct SecondView: View {
    @State var showAlert = true
    
    var body: some View {
        // i want to show alert when navigate to this view
        VStack{
            Text("Second View")
                .alert(isPresented: $showAlert) {
                    Alert(title: Text("You are in second view"))
                }
        }
    }
}

你可以帮助我 ?

标签: iosswiftxcodeswiftui

解决方案


出现时将值更改showAlert为true VStack,就像那样

struct SecondView: View {
    @State var showAlert = false 
    
    var body: some View {
        // i want to show alert when navigate to this view
        VStack{
            Text("Second View")
                .alert(isPresented: $showAlert) {
                    Alert(title: Text("You are in second view"))
                }
        }.onAppear{
          showAlert = true
        }
    }
}

推荐阅读