问题
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