In iOS 13.4, SwiftUI ObservedObject in nested ForEach no longer updates View as in iOS 13.3 [duplicate]

﹥>﹥吖頭↗ 提交于 2021-02-11 17:42:18

问题


Here is a simple code to show the problem. It displays a list of name in OberservedObject data, which is in nested ForEach. When data is updated by clicking the button, the view should be updated. The code works perfectly in iOS 13.3 for both simulators and devices, i.e. the view will be updated after clicking the button. But it fails in iOS 13.4 for both simulators and devices, i.e. the view is never updated. Any idea what's going on here?

class Data: ObservableObject {
  @Published var names = ["Alice", "Jason", "Tom"]
}

struct ContentView: View {
  @ObservedObject var data = Data()

  var body: some View {
    VStack(spacing: 10) {
      ForEach(0..<2) { _ in
        ForEach(0..<self.data.names.count) { i in
          Text(self.data.names[i])
        }
      }

      Button(action: { self.data.names[0] = "Mary" }) {
        Text("Click me")
          .padding()
          .border(Color.black, width: 4)
      }
    }
  }
}

回答1:


Thanks to user3441734! The working code is updated as the below.

class Data: ObservableObject {
  @Published var names = ["Alice", "Jason", "Tom"]
}

struct ContentView: View {
  @ObservedObject var data = Data()

  var body: some View {
    VStack(spacing: 10) {
      ForEach(0..<2, id: \.self) { _ in
        ForEach(0..<self.data.names.count, id: \.self) { i in
          Text(self.data.names[i])
        }
      }

      Button(action: { self.data.names[0] = "Mary" }) {
        Text("Click me")
          .padding()
          .border(Color.black, width: 4)
      }
    }
  }
}


来源:https://stackoverflow.com/questions/60878310/in-ios-13-4-swiftui-observedobject-in-nested-foreach-no-longer-updates-view-as

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!