1

我目前有一个List位于模态 ( .sheet) 视图中的,我正在尝试将点击的值从它检索回前一个视图。我怎样才能做到这一点?

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)
    }
}

在这个例子中,我想在Textwith上设置文本。"Selected item"

4

1 回答 1

1

你不应该!您的 .sheet 视图应该更新您的模型,然后如果需要,这些更改会反映在您之前的视图中。

这是一个很好的资源来解释这种交流: https ://youtu.be/4GjXq2Sr55Q

于 2020-08-20T03:48:42.887 回答