3

我正在使用 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 的这种结构。

4

1 回答 1

1

它没有显示如何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
           }
        }
    ...
于 2020-02-14T17:05:32.137 回答