在iOS 13.4中,嵌套ForEach中的SwiftUI ObservedObject不再像在iOS 13.3中那样更新视图

时间:2020-03-27 00:40:34

标签: ios swiftui

这是显示问题的简单代码。它在嵌套的ForEach中的OberservedObject data中显示名称列表。通过单击按钮更新data时,应更新视图。该代码在iOS 13.3中对于模拟器和设备均可完美运行,即在单击按钮后将更新视图。但是它在iOS 13.4中针对模拟器和设备均失败,即视图从未更新过。知道这里发生了什么吗?

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 个答案:

答案 0 :(得分:0)

感谢user3441734!工作代码如下更新。

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)
      }
    }
  }
}