I have an array of structs, which ForEach uses to generate SubViews. When I delete one of object from that array, one of SubViews disappear as expected. But when I pass an EnvironmentObject to the SubView and that view gets deleted, app crashes. By the way, its a Mac App.
import SwiftUI
struct Item: Identifiable {
var id = UUID().uuidString
var title: String
}
class Data: ObservableObject {
@Published var items: [Item] = [Item(title: "One"), Item(title: "Two"), Item(title: "Three")]
func removeOneItem (){
if items.count > 0 {
items.remove(at: 0)
}
}
}
struct ContentView: View {
@StateObject var data = Data()
var body: some View {
VStack {
ForEach(data.items.indices, id:\.hashValue) { i in
SubView(item: $data.items[i]).environmentObject(data)
}
Button(action: data.removeOneItem) {Text("Remove one item").foregroundColor(.red)}
}
}
}
struct SubView: View {
@Binding var item: Item
@EnvironmentObject var data: Data // <- works only without this line
var body: some View {
Button { self.item.title = "tapped"} label: {Text(item.title)}
}
}
Any ideas?