gpt4 book ai didi

swift - 从 View 模型中关闭 View [MODAL PAGE]

转载 作者:行者123 更新时间:2023-12-03 09:29:30 26 4
gpt4 key购买 nike

我正在使用 swiftUI 并结合,我的虚拟机中有一些业务逻辑。有些结果不得不否定我的观点。

我在某些 View 中使用了这个:

@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

self.presentationMode.wrappedValue.dismiss()


我想在我的 View 模型中使用类似的东西。

最佳答案

您不会在 SwiftUI 中以命令式的方式进行解雇。 .相反,您使用 .sheet通过将其绑定(bind)到将从该 View 模型中变异的 bool 属性来查看 View 。

编辑:

After answering a follow-up question, I came up with a different approach. It plays nice if the dismissal is actually needed to be done from inside the modally presented View itself.



您可以通过实现自定义 Publisher 来实现此目的。将使用 .send()允许您向订阅者发送特定值的方法(在本例中为您的 View )。您将使用 onReceive(_:perform:) View 上定义的方法 的协议(protocol)SwiftUI 订阅自定义 Publisher的输出流你定义的。里面 perform操作关闭,您将可以访问发布者的最新发出值,您将实际解雇您的 View .

理论说的够多了,可以看代码,应该不难理解,如下:
import Foundation
import Combine

class ViewModel: ObservableObject {
var viewDismissalModePublisher = PassthroughSubject<Bool, Never>()
private var shouldDismissView = false {
didSet {
viewDismissalModePublisher.send(shouldDismissView)
}
}

func performBusinessLogic() {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.shouldDismissView = true
}
}
}

和意见同行是:
import SwiftUI

struct ContentView: View {
@State private var isDetailShown = false
var body: some View {
VStack {
Text("Hello, World!")
Button(action: {
self.isDetailShown.toggle()
}) {
Text("Present Detail")
}
}
.sheet(isPresented: $isDetailShown) {
DetailView()
}
}
}

struct DetailView: View {
@ObservedObject var viewModel = ViewModel()
@Environment(\.presentationMode) private var presentationMode
var body: some View {
Text("Detail")
.navigationBarTitle("Detail", displayMode: .inline)
.onAppear {
self.viewModel.performBusinessLogic()
}
.onReceive(viewModel.viewDismissalModePublisher) { shouldDismiss in
if shouldDismiss {
self.presentationMode.wrappedValue.dismiss()
}
}
}
}

老答案:

关于 View 模型中业务逻辑更改的 View 解除的一个非常简单的实现是:
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
Text("Hello, World!")

// the animation() modifier is optional here
.sheet(isPresented: $viewModel.isSheetShown.animation()) {
Text("Sheet Presented")
}

// From here - for illustration purpose
.onAppear {
self.viewModel.perform()
}
// To here

}
}

class ViewModel: ObservableObject {
@Published var isSheetShown = false

func perform() {
// this just an example. In real application, you will be responsible to
// toggle between the states of the `Bool` property
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.isSheetShown.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.isSheetShown.toggle()
}
}
}
}

关于swift - 从 View 模型中关闭 View [MODAL PAGE],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59103163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com