SwiftUI View 和 ViewModel 使用绑定和观察变量进行修改
SwiftUI View and ViewModel Modifying with Binding and Observed variables
我有一个 View 和一个 ViewModel,我想在 ViewModel 中设置一些变量,然后在 View 中读取和设置它们。在 ViewModel 中,我有一个 @Published 变量。当我尝试修改视图中变量的值时,我得到的错误是:'Cannot assign to property: '$testModel' is immutable' 和 'Cannot assign value of type 'String' to type 'Binding' .有没有办法做到这一点?我现在的代码如下:
查看
struct TestView: View {
@ObservedObject var testModel: TestViewModel = TestViewModel()
var body: some View {
VStack(alignment: .center, spacing: 4) {
Button(action: {
$testModel.test = "test2"
}) {
Text("[ Set value ]")
}
}
}
}
ViewModel
class TestViewModel: ObservableObject {
@Published var test = "test"
}
因为不需要 Binding
来设置值,所以不需要 $testModel
,只需要 testModel
.
将代码更改为:
Button(action: {
testModel.test = "test2"
}) {
Text("[ Set value ]")
}
还值得注意的是,您应该在此处使用 @StateObject
而不是 @ObservedObject
,以防止 TestViewModel
可能被多次初始化。
我有一个 View 和一个 ViewModel,我想在 ViewModel 中设置一些变量,然后在 View 中读取和设置它们。在 ViewModel 中,我有一个 @Published 变量。当我尝试修改视图中变量的值时,我得到的错误是:'Cannot assign to property: '$testModel' is immutable' 和 'Cannot assign value of type 'String' to type 'Binding' .有没有办法做到这一点?我现在的代码如下:
查看
struct TestView: View {
@ObservedObject var testModel: TestViewModel = TestViewModel()
var body: some View {
VStack(alignment: .center, spacing: 4) {
Button(action: {
$testModel.test = "test2"
}) {
Text("[ Set value ]")
}
}
}
}
ViewModel
class TestViewModel: ObservableObject {
@Published var test = "test"
}
因为不需要 Binding
来设置值,所以不需要 $testModel
,只需要 testModel
.
将代码更改为:
Button(action: {
testModel.test = "test2"
}) {
Text("[ Set value ]")
}
还值得注意的是,您应该在此处使用 @StateObject
而不是 @ObservedObject
,以防止 TestViewModel
可能被多次初始化。