当传递给视图的ObservedObject被更新时,SwiftUI不会更新吗?

问题描述 投票:1回答:1

我有一个称为SearchResults的视图。每当传递给它的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
    }
}

侧面说明:VModel有一个类型为[String]的数组,称为searchResults,我认为只要更新searchResults数组,此视图就应该更新。

我有一个称为SearchResults的视图。每当传递给它的ObservedObject更改时,它都应该更新,但是View不会使用新值更新,我不确定为什么。导入SwiftUI结构...

swift view swiftui observedobject
1个回答
0
投票

很抱歉给大家带来的困惑,显然我真的很傻。我正在创建一个新的ViewModel()实例,而不是传入ContentView中声明的实例。

© www.soinside.com 2019 - 2024. All rights reserved.