0

我有一个显示模式表的主视图。由于我有多个模式,我使用 enum 和 State 来控制显示哪个工作表。

@State var activeSheet: Sheet?

在我的主视图中:

    Button(action: {
        activeSheet = .settings
    }, label: {
        Text(“Button”)
    })

   .sheet(item: $activeSheet) { sheet in
        switch sheet {
        case .info:
          InfoView()
        case .settings:
          SettingsView()
        }
      }

设置视图:

struct SettingsView: View {
    @Environment(\.presentationMode) private var presentationMode
    @EnvironmentObject var model: MainModel
    
    var body: some View {
        Button("Action") {
            model.myFunction()
        }
    }
}

在我的 InfoView 表中,我有一个按钮,可以调用 EnvironmentObject 中的函数。在 EnvironmentObject 中完成功能后,如何关闭工作表?

每个视图都链接到同一个 EnvironmentObject 顺便说一句。

谢谢!

4

1 回答 1

0

根据您部署的最低 iOS 版本,您有两种选择:

如果您的最低 iOS 版本为 <= iOS 14,则在两者中都InfoView使用SettingsViewsystem environment \.presentationMode

struct SettingsView: View {
    @EnvironmentObject var model: MainModel
    @Environment(\.presentationMode) private var presentationMode

    var body: some View {
        Button("Dismiss") {

            /// ... Do something here prior to dismissing the sheet.
            model.MyFunction(email: email, password: password) {
                presentationMode.wrappedValue.dismiss()
            }
        }
    }
}

在您的最低 iOS 版本上是 iOS 15,同时InfoView使用SettingsView系统环境\.dismiss

struct SettingsView: View {
    @EnvironmentObject var model: MainModel
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        Button("Dismiss") {

            /// ... Do something here prior to dismissing the sheet.
            model.MyFunction(email: email, password: password) {
                dismiss()
            }
        }
    }
}

MainModel类:

class MainModel: ObservableObject {
    func myFunction(email: String, password: String, onSuccess: (() -> Void)? = nil) {         
        auth.signIn(withEmail: email, password: password) { [weak self] result, error in
            if result == nil, error != nil {
                 self?.showAlert = true
            } else {
                 guard result != nil, error == nil else { return }
                 /* Success */
                 self?.signedIn = true
                 onSuccess?()
            }
        }
    }
}

替代解决方案:

如果您的最低部署目标是 >= iOS 14,您可以像这样监听环境对象属性的更改:

struct SettingsView: View {
    @EnvironmentObject var model: MainModel
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        Button("Dismiss") {
            model.MyFunction(email: email, password: password)
        }
        .onChange(of: model.signedIn) { signedIn in
            if signedIn {
                dismiss()
            }
        }
    }
}
于 2021-10-09T13:51:59.420 回答