简体   繁体   中英

SwiftUI return value from modal view

I currently have a List that is inside a modal ( .sheet ) view, and I'm trying to retrieve the tapped value from it back to the previous view. How can I achieve this?

import SwiftUI

struct ContentView: View {
    @State var showingModal: Bool = false
    
    var body: some View {
        VStack {
            Button(action: {
                self.showingModal.toggle()
            }) {
                Text("Tap me!")
            }.sheet(isPresented: $showingModal, onDismiss: {
                print("Dismissed")
            }) {
                ModalView(isShowing: self.$showingModal)
            }
            Text("Selected Item: ")
        }
    }
}

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

import SwiftUI

struct ModalView: View {
    @State private var names = ["Foo", "Bar"]
    @Binding var isShowing: Bool
    
    var body: some View {
        List(names, id: \.self) { name in
            HStack {
                Text("\(name)")
                Spacer()
            }
            .contentShape(Rectangle())
            .onTapGesture {
                print(name)
                self.isShowing = false
            }
        }
    }
}

struct ModalView_Previews: PreviewProvider {
    @State static var value = true
    
    static var previews: some View {
        ModalView(isShowing: self.$value)
    }
}

I'd like to set the text on the Text with "Selected item" in this example.

You shouldn't. Your.sheet view should update your model then this changes got reflected in your previous view if needed.

Here is a good resource explaining this communication: https://youtu.be/4GjXq2Sr55Q

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