ios - SwiftUI View 在更改 @ObservedObject 时未更新

标签 ios swift swiftui observableobject

这是一个简单的基于 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))"
    }
}
从 View 模型内部更新模型时, View 不会更新。
文本最终应该会产生一些介于 1 和 10 之间的随机数。请让我知道我哪里出错了。

最佳答案

这是因为您的Test查看观察 viewModel但不是 viewModel.model在您的场景中不会更改,因为它是引用类型
以下是解决方案

func change() {
    model.condition.toggle()
    model.stri = "\(Int.random(in: 1...10))"

    self.objectWillChange.send()    // << this one !!
}

关于ios - SwiftUI View 在更改 @ObservedObject 时未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62682422/

相关文章:

ios - iOS8 证书错误的 OTA 部署

ios - 将 Playground 添加到现有工作区(使用 cocoapods)

ios - 无效的索引路径错误

ios - 使用 ViewModel 的通用 View SwiftUI

swiftui - SwiftUI 中的全局警报

objective-c - 单元测试前备份CoreData

ios - xcode 跳转条符号表示

swift - 如何在 Swift 中创建一个简单的 UIViewController 并将其设置为起始 View

ios - 如何在 Swift 的 NSMutableDictionary 中为键的特定索引附加一个值的数组

ios - SwiftUI 应用程序崩溃并出现 "attempt to insert row 2 into section 0, but there are only 2 rows in section 0 after the update"错误