我有一个结构数组,ForEach 使用它来生成子视图。当我从该数组中删除一个对象时,其中一个子视图会按预期消失。但是当我将 EnvironmentObject 传递给 SubView 并且该视图被删除时,应用程序崩溃。顺便说一句,它是一个 Mac 应用程序。
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)}
}
}
有任何想法吗?