SwiftUI如何在关闭时将数据传递到上一个屏幕
Posted
技术标签:
【中文标题】SwiftUI如何在关闭时将数据传递到上一个屏幕【英文标题】:SwiftUI how to pass data to previous screen on dismiss 【发布时间】:2021-07-16 11:59:11 【问题描述】:我想将关闭 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
【问题讨论】:
【参考方案1】:您可以为此使用@Binding
(或@StateObject
、@ObservedObject
、@Environmentobject
和@ObservableObject
,使用MVVM 设计模式)
以下代码是使用@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
【讨论】:
感谢@Taeeun onDismiss 我们可以日期```swift .sheet(isPresented: $showModel, onDismiss: print("(filter.fromDate) and (filter.toDate)") , 内容: FilterView(filter: $filter) )''' 还有其他方法吗?我们必须创建对象对吗?@State var filter: Filter(fromDate: "", toDate: "")
@iosDeveloper 欢迎您!我可以再问你一次,你是什么意思?如果你想创建没有初始值的对象,比如@State var filter: Filter()
,那么你可以使用可选的(在类型末尾使用?
),比如var fromDate: String?
和var toDate: String?
。然后你可以使用@State var filter: Filter()
并且你必须将这个filter.fromDate
更改为filter.fromDate ?? "no date"
,因为它现在是可选值。 (或filter.fromDate!
)以上是关于SwiftUI如何在关闭时将数据传递到上一个屏幕的主要内容,如果未能解决你的问题,请参考以下文章
将参数传递到上一个屏幕并使用react-navigation进行更新