@View中的Binding值是从外部获取的,如何控制ViewModel中的值,最佳实践是什么
import SwiftUI
import Combine
struct ContentView: View {
@State var isPresented = false
var body: some View {
VStack {
Button("show popup") {
isPresented = true
}
}
.sheet(isPresented: $isPresented) {
PopupView(isPresented: $isPresented)
}
}
}
struct PopupView: View {
@Binding var isPresented: Bool
@StateObject private var vm = PopupViewModel()
var body: some View {
Button("dimiss") {
// isPresented = false
vm.dismiss()
}
}
private class PopupViewModel: ObservableObject {
func dismiss() {
// TODO: how to change isPresented
// how to pass @Binding to VM
}
}
}
我尝试在查看时将块传递给vm
onAppear
,然后更改块中的View属性,就像这样
struct PopupView: View {
@Binding var isPresented: Bool
@StateObject private var vm = PopupViewModel()
var body: some View {
Button("dimiss") {
vm.dismiss()
}
.onAppear {
vm.dismissBlock = {
isPresented = false
}
}
}
private class PopupViewModel: ObservableObject {
var dismissBlock: (()->Void)?
func dismiss() {
dismissBlock?()
}
}
}
但这不是最好的方法,有什么好的想法吗?
在代码中,您已经提供了没有理由引入视图模型。您的视图可以提供所有功能。如果您有事实来源,那么您可以添加一个 ObservableObject。保持简单!