SwiftUI,如何在 API 成功调用 returns 时关闭当前呈现的视图
SwiftUI, How to dismiss current presenting View when API call returns successfully
我正在使用 SwiftUI,我正在尝试实现一个简单的逻辑操作,但无法理解 SwiftUI 操作层次结构。
我有一个 API 调用这样的东西,
final class TaskData: ObservableObject {
@Published var updatedFields = false
@Published var updateMsg = ""
func updateFields()
{
//Some API Call
.whenSuccess { (response) in
DispatchQueue.main.async {
self.updatedFields = true
self.updateMsg = "Successfully updated fields"
//Send Request to dismiss current View ???
}
}
}
}
现在,我有一个类似这样的视图,根据请求我想关闭这个视图,但我找不到任何方法,
struct TaskView: View {
@Environment(\.presentationMode) var currentView: Binding<PresentationMode>
@EnvironmentObject var taskData: TaskData
var body : some View {
//Some Views here ////
//Need Some code here to dismiss currentView?????
.navigationBarItems(trailing: Button(action: {
}, label: {
Text("Done")
}).onTapGesture {
self.taskData.updateFields() // Method Call to Update fields
})
}
如果有人能详细解释一下这个东西,我是SwiftUI的新手,我看过很多教程,但无法理解swift的这种结构。
没有显示 TaskView
是如何呈现的,但是在给定的代码快照中有 presentationMode
让我们假设它是有效的,所以方法可能如下
@Environment(\.presentationMode) var presentationMode //better to name it same,
//type is extracted from Environment
@EnvironmentObject var taskData: TaskData
var body : some View {
//Some Views here ////
SomeView()
.onReceive(taskData.$updatedFields) { success in
if success {
self.presentationMode.wrappedValue.dismiss() // dismiss self
}
}
...
我正在使用 SwiftUI,我正在尝试实现一个简单的逻辑操作,但无法理解 SwiftUI 操作层次结构。
我有一个 API 调用这样的东西,
final class TaskData: ObservableObject {
@Published var updatedFields = false
@Published var updateMsg = ""
func updateFields()
{
//Some API Call
.whenSuccess { (response) in
DispatchQueue.main.async {
self.updatedFields = true
self.updateMsg = "Successfully updated fields"
//Send Request to dismiss current View ???
}
}
}
}
现在,我有一个类似这样的视图,根据请求我想关闭这个视图,但我找不到任何方法,
struct TaskView: View {
@Environment(\.presentationMode) var currentView: Binding<PresentationMode>
@EnvironmentObject var taskData: TaskData
var body : some View {
//Some Views here ////
//Need Some code here to dismiss currentView?????
.navigationBarItems(trailing: Button(action: {
}, label: {
Text("Done")
}).onTapGesture {
self.taskData.updateFields() // Method Call to Update fields
})
}
如果有人能详细解释一下这个东西,我是SwiftUI的新手,我看过很多教程,但无法理解swift的这种结构。
没有显示 TaskView
是如何呈现的,但是在给定的代码快照中有 presentationMode
让我们假设它是有效的,所以方法可能如下
@Environment(\.presentationMode) var presentationMode //better to name it same,
//type is extracted from Environment
@EnvironmentObject var taskData: TaskData
var body : some View {
//Some Views here ////
SomeView()
.onReceive(taskData.$updatedFields) { success in
if success {
self.presentationMode.wrappedValue.dismiss() // dismiss self
}
}
...