本文介绍了在 iOS 13.4 中,嵌套 ForEach 中的 SwiftUI ObservedObject 不再像在 iOS 13.3 中那样更新 View的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的代码来显示问题.它在嵌套的 ForEach 中显示 OberservedObject data 中的名称列表.当通过单击按钮更新 data 时,应该更新视图.该代码在 iOS 13.3 中完美适用于模拟器和设备,即单击按钮后视图将更新.但它在 iOS 13.4 中对于模拟器和设备都失败了,即视图永远不会更新.知道这里发生了什么吗?

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

推荐答案

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

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

这篇关于在 iOS 13.4 中,嵌套 ForEach 中的 SwiftUI ObservedObject 不再像在 iOS 13.3 中那样更新 View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 09:22