如何解决SwiftUI MVVM绑定
如何将@Binding
传递到viewmodel中。
我们来看一个简单的例子,
struct TopView: View {
@State var isPresented: Bool
var body: some View {
SubView(isPresented: $isPresented)
}
}
struct SubView: View {
@Binding var isPresented: Bool
}
然后,如果我们要使用MVVM模式,
在@Binding
中使用ObservableObject
是否安全?
例如,书写安全吗
struct TopView: View {
@State var isPresented: Bool
var body: some View {
SubView(model: Subviewmodel(isPresented: $isPresented))
}
}
struct SubView: View {
@Observedobject var model: Subviewmodel
}
// In "Subviewmodel.swift"
import Foundation
import Combine
import SwiftUI
public final class Subviewmodel: Observedobject {
@Binding var isPresented: Bool
public init(isPresented: Binding<Bool>) {
self._isPresented = isPresented
}
}
你会怎么做?类似,包括如何将environmentObject传递到视图模型中?
解决方法
您正在描述ObservableObject
的基本用法。
@Binding
和@State
仅在View
Apple SwiftUI教程可能对您很有帮助,因此您可以了解SwiftUI的概念。 https://developer.apple.com/tutorials/swiftui/
您的代码中存在一些基本错误,我在下面的代码中提到了更改。
import SwiftUI
struct PassingBinding: View {
var body: some View {
TopView1()//Best Practice
//TopView2()//Singleton Pattern
}
}
///This is the best way to do it
///https://developer.apple.com/tutorials/swiftui/handling-user-input
struct TopView1: View {
@ObservedObject var model: SubViewModel = SubViewModel()
var body: some View {
VStack{
SubView1().environmentObject(model)
Button(action: {
self.model.isPresented.toggle()
},label: {
Text("Toggle isPresented")
})
}
}
}
struct SubView1: View {
@EnvironmentObject var model: SubViewModel
var body: some View {
Text("SubView - isPresented == \(model.isPresented.description)")
}
}
///Another way that has some specifc uses is to use a Singleton model
///https://developer.apple.com/documentation/swift/cocoa_design_patterns/managing_a_shared_resource_using_a_singleton
struct TopView2: View {
@ObservedObject var model: SubViewModel = SubViewModel.shared
var body: some View {
VStack{
SubView2()
Button(action: {
self.model.isPresented.toggle()
},label: {
Text("Toggle isPresented")
})
} }
}
struct SubView2: View {
@ObservedObject var model: SubViewModel = SubViewModel.shared
var body: some View {
Text("SubView - isPresented == \(model.isPresented.description)")
}
}
///This item can be Observed "ObservableObject" vs I am Observing this object "ObservedObject"
///https://developer.apple.com/documentation/combine/observableobject
public final class SubViewModel: ObservableObject {
static let shared: SubViewModel = SubViewModel()//Singleton Pattern
@Published var isPresented: Bool = false //Initialize here this is the source for the View
//@Binding and @State is are only used in View struct not in an ObservableObject.https://developer.apple.com/documentation/swiftui/binding
}
struct PassingBinding_Previews: PreviewProvider {
static var previews: some View {
PassingBinding()
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。