SwiftUI: Clear Modal state or Reinitialize

前端 未结 2 1477
栀梦
栀梦 2021-02-02 18:22

I have a SwiftUI modal that I would like to either clear the state of or reinitialize. Reinitalizing would be preferred considering the fact that this modal can open other modal

2条回答
  •  余生分开走
    2021-02-02 18:56

    You can reinitialize your Modal in .onAppear(). This example works on Beta 3.

    import SwiftUI
    
    struct ModalView : View {
    
        @Environment(\.isPresented) var isPresented: Binding?
    
        @State var textName: String = ""
    
        var body: some View {
    
            NavigationView {
    
                Form {
                    Section() {
                         TextField("Name", text: self.$textName)
                            .textFieldStyle(.roundedBorder)
                    }
                }
                .listStyle(.grouped)
                    .navigationBarTitle(Text("Add Name"), displayMode: .large)
                    .navigationBarItems(leading: Button(action:{ self.dismiss() })
                    { Text("Cancel") },
                                        trailing: Button(action:{ self.dismiss() })
                                        { Text("Save") } )
                    .onAppear(perform: {
                        self.textName = ""
                    })
            }
        }
    
        func dismiss() {
            self.isPresented?.value = false
        }
    
    }
    
    struct DetailView : View {
    
        var body: some View {
    
            PresentationLink(destination: ModalView())
            { Text("Present") }
        }
    
    }
    
    struct ContentView : View {
    
        var body: some View {
    
            NavigationView {
                NavigationLink(destination: DetailView())
                { Text("Navigate") }
            }
        }
    }
    

提交回复
热议问题