简体   繁体   English

SwiftUI 从不同的视图添加新项目时,ObservedObject 不会更新

[英]SwiftUI ObservedObject does not updated when new items are added from a different view

I have a view model which handles the loading of new data once the app launches and when a new item is added.我有一个视图 model ,它在应用程序启动和添加新项目时处理新数据的加载。 I have an issue when it comes to showing new items when are added from a new view, for example, a sheet or even a NavigationLink .从新视图(例如工作sheet甚至NavigationLink )添加新项目时,我在显示新项目时遇到了问题。

View Model查看 Model

class GameViewModel: ObservableObject {
    //MARK: - Properties
    @Published var gameCellViewModels = [GameCellViewModel]()
    var game = [GameModel]()
    
    init() {
        loadData()
    }
    
    func loadData() {
        if let retrievedGames = try? Disk.retrieve("games.json", from: .documents, as: [GameModel].self) {
            game = retrievedGames
        }
        
        self.gameCellViewModels = game.map { game in
            GameCellViewModel(game: game)
        }
        print("Load--->",gameCellViewModels.count)
    }
    
    func addNew(game: GameModel){
        self.game.append(game)
        saveData()
        loadData()
    }
    
    private func saveData() {
        do {
            try Disk.save(self.game, to: .documents, as: "games.json")
        }
        catch let error as NSError {
            fatalError("""
                Domain: \(error.domain)
                Code: \(error.code)
                Description: \(error.localizedDescription)
                Failure Reason: \(error.localizedFailureReason ?? "")
                Suggestions: \(error.localizedRecoverySuggestion ?? "")
                """)
        }
    }
}

View to load the ViewModel data, leading add button is able to add and show data but the trailing which opens a new View does not update the view.视图加载 ViewModel 数据, leading添加按钮能够添加和显示数据,但打开新视图的trailing不会更新视图。 I have to kill the app to get the new data.我必须杀死应用程序才能获取新数据。

    NavigationView{
        List {
            ForEach(gameList.gameCellViewModels) { gameList in
                CellView(gameCellViewModel: gameList)
            }
        }.navigationBarTitle("Games Played")
            .navigationBarItems(leading: Text("Add").onTapGesture {
                let arr:[Int] = [1,2,3]
                self.gameList.addNew(game: GameModel(game: arr))
                }, trailing: NavigationLink(destination: ContentView()){
                    Text("Play")
            })
    }

Play View sample播放查看示例

@State var test = ""
var body: some View {
    VStack(){
        TextField("Enter value", text: $test)
            .keyboardType(.numberPad)
        
        Button(action: {
            var arr:[Int] = []
            arr.append(Int(self.test)!)
            self.gameList.addNew(game: GameModel(game: arr))
        }) {
            Text("Send")
        }
    }
}

To what I can see the issue seems to be here:据我所知,问题似乎在这里:

List {
   // Add id: \.self in order to distinguish between items 
   ForEach(gameList.gameCellViewModels, id: \.self) { gameList in                    
      CellView(gameCellViewModel: gameList)                    
   }
}

ForEach needs something to orientate itself on in order to know what elements are already displayed and which are not. ForEach 需要一些东西来定位自己,以便知道哪些元素已经显示,哪些没有。

If this did not solve the trick.如果这没有解决问题。 Please update the code you provided to Create a minimal, Reproducible Example请更新您提供的代码以创建一个最小的、可重现的示例

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

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