【问题标题】:SwiftUI view not getting updated on changing @ObservedObjectSwiftUI 视图在更改 @ObservedObject 时未更新
【发布时间】:2020-10-22 05:32:40
【问题描述】:

这是一个简单的基于 MVVM 的 TestView:

import SwiftUI

public struct Test: View {
        
    @ObservedObject public var viewModel = TestViewModel()
    
    public init() {
        
    }
    
    public var body: some View {
        VStack {
            Text(viewModel.model.stri)
            Button(action: {
                self.viewModel.change()
            }) {
                Text("Change")
            }
        }.padding(50)
    }
}

public class TestModel {
    
    @Published public var condition: Bool = false
    @Published var stri = "Random numbers"
    
}

public class TestViewModel: ObservableObject {
    
    @Published var model = TestModel()
    
    func change() {
        model.condition.toggle()
        model.stri = "\(Int.random(in: 1...10))"
    }
}

从视图模型内部更新模型时,视图不会更新。 文本最终应该会产生一些介于 1 和 10 之间的随机数。请让我知道我哪里出错了。

【问题讨论】:

    标签: ios swift swiftui observableobject


    【解决方案1】:

    这是因为您的 Test 视图观察到 viewModel 而不是 viewModel.model 在您的场景中不会更改,因为它是一个引用类型

    以下是解决办法

    func change() {
        model.condition.toggle()
        model.stri = "\(Int.random(in: 1...10))"
    
        self.objectWillChange.send()    // << this one !!
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 1970-01-01
      • 2021-02-17
      • 2020-12-21
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多