简体   繁体   中英

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

I have a view called 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.

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..?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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