简体   繁体   中英

Fire some code when dismissing SwiftUI modal

I have a modal built with SwitftUI which has a TextField with onCommit: code which saves user input from @State variable to file when user taps "return" on keyboard.

However, if user types something inside TextField and then dismisses the modal without pressing "return", the onCommit: code doesn't fire and user input stays unsaved. How do I fire some code accessing inner variable of my modal View when it is dismissed?

Try the following:

Instead having a private @State var on your modal, make it an internal @Binding that you pass into the modal from the call site. This way the modified bound variable is available on both the caller and the modal view.

import SwiftUI

struct ContentView: View {
    @State var dismiss = false
    @State var txt = ""
    @State var store = ""
    var body: some View {
        VStack {
        Text("modal").sheet(isPresented: $dismiss, onDismiss: {
            self.store = self.txt
        }) {
            TextField("txt", text: self.$txt) {
                self.store = self.txt
            }.padding().border(Color.red)
        }.onTapGesture {
            self.dismiss.toggle()
        }
            Text(store)
        }
    }
}

struct ContetView_Preview: 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