简体   繁体   English

当传递到视图中的 ObservedObject 更新时,SwiftUI 不会更新?

[英]When an ObservedObject passed into a view is updated, the SwiftUI doesn't update?

I have a view called SearchResults.我有一个名为 SearchResults 的视图。 It should update whenever the ObservedObject passed into it changes, but the View is not updating with the new values and I'm not sure why.每当传入的 ObservedObject 发生更改时,它都应该更新,但是 View 没有使用新值更新,我不知道为什么。

import SwiftUI

struct SearchResults: View {
    @ObservedObject var VModel: ViewModel
    var body: some view {
        List {
            ForEach(self.VModel.searchResults, id: \.self) { result in 
                Text(result)
            }
        }
    }
}


class ViewModel: ObservableObject {
    @Published var searchResults: [String] = []

    func findResults() {
        //Do the update to 'searchResults' here
        //This function is called at another point in the code in a pretty big file...I think it might make it more confusing to have like a couple hundred more lines of code in here
    }
}

Side Note: VModel has an array of type [String] called searchResults, and I thought this view should update whenever the searchResults array is updated..?旁注:VModel 有一个类型为 [String] 的数组,称为 searchResults,我认为这个视图应该在 searchResults 数组更新时更新..?

Sorry for all the confusion everyone, evidently I'm really stupid.对不起大家的困惑,显然我真的很愚蠢。 I was creating a new ViewModel() instance instead of passing in the one declared in ContentView我正在创建一个新的 ViewModel() 实例,而不是传入 ContentView 中声明的实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM