1

我想将关闭数据传递presentViewController到上一个屏幕。在这里,我想使用块将数据作为 UIKitApp 传递到上一个屏幕。但我不知道传递数据。我们options必须将数据传递回什么?

struct ContentView: View {
    @State var showModel = false
    var body: some View {
        VStack {
            Button(action: {
                showModel.toggle()
            }, label: {
                Text("Show filters")
            }).sheet(isPresented: $showModel, content: {
                FilterView()
            })
        }
    }
}

struct FilterView: View {
    @Environment(\.presentationMode) var presentationMode

    var onDismiss: ((_ model: Filter) -> Void)?

    var body: some View {
        
        VStack {
            Button(action: {
                // Pass data from here to ContentView
                let filter = Filter(fromDate: "10/07/2021", toDate: "12/07/2021")
                onDismiss?(filter)
                presentationMode.wrappedValue.dismiss()
            }, label: {
                Text("Applay Filters")
            }).padding()
        }.padding()
    }
}

struct Filter {
    var fromDate: String
    var toDate: String
}
4

1 回答 1

5

您可以使用@Binding它(或@StateObject, @ObservedObject,@Environmentobject使用@ObservableObjectMVVM 设计模式)

下面的代码是使用@Binding 的示例。

添加/编辑的行

Text("\(filter.fromDate) and \(filter.toDate)") // to see the changed values

@State var filter = Filter(fromDate: "", toDate: "") // in ContentView

@Binding var filter: Filter // in FilterView

FilterView(filter: $filter) // $ used for @Binding parameter

完整代码

struct ContentView: View {
    @State var showModel = false
    @State var filter = Filter(fromDate: "", toDate: "")
    
    var body: some View {
        VStack {
            Text("\(filter.fromDate) and \(filter.toDate)")
            Button(action: {
                showModel.toggle()
            }, label: {
                Text("Show filters")
            }).sheet(isPresented: $showModel, content: {
                FilterView(filter: $filter)
            })
        }
    }
}

struct FilterView: View {
    @Environment(\.presentationMode) var presentationMode

    var onDismiss: ((_ model: Filter) -> Void)?
    @Binding var filter: Filter

    var body: some View {
        
        VStack {
            Button(action: {
                // Pass data from here to ContentView
                filter = Filter(fromDate: "10/07/2021", toDate: "12/07/2021")
                onDismiss?(filter)
                presentationMode.wrappedValue.dismiss()
            }, label: {
                Text("Applay Filters")
            }).padding()
        }.padding()
    }
}

struct Filter {
    var fromDate: String
    var toDate: String
}

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

于 2021-07-16T12:14:41.273 回答