【发布时间】:2021-04-25 07:54:24
【问题描述】:
我放弃了。这就是问题所在:我尝试将数组names 作为 ObservableObject 加载到我的列表中。名称必须以 Bindings 的形式连接到 TextField:
class Users: ObservableObject {
@Published var names = ["Adele", "Taylor", "Michael"]
}
我的 ContentView 如下所示:
@EnvironmentObject var users: Users
var body: some View {
NavigationView {
List {
ForEach(0..<users.names.count, id: \.self) {
TextField("titel", text: $users.names[$0])
}
.onDelete(perform: delete)
}
.navigationBarItems(trailing: EditButton())
.navigationTitle("bug")
}
}
func delete(at offsets: IndexSet) {
users.names.remove(atOffsets: offsets)
}
environmentObject 链接到 ContentView():
ContentView()
.environmentObject(Users())
一切正常,但是当我尝试删除一行时,它看起来很有趣:下面的行向右滑动,应该删除的行向上移动。它甚至不一致,但取决于我开始删除的项目。看到这个.gif:
到目前为止我尝试过的:
我认为该错误与无法识别的列表有关。所以我尝试使用类似的东西:
ForEach(users.names, id: \.id) {
...
}
使用带有id: UUID() 的新用户类
但是使用对象本身而不是0..<users.names.count 只会导致问题,即我不能在我的 ForEach-Loop 中使用绑定。也可以看看:
@Binding and ForEach in SwiftUI
所以我的问题是:
- 我在这里错过了什么吗?我是 SwiftUI 的新手,所以我很有可能没有掌握基本知识。
- 我可以在 ForEach-Loop 中使用绑定,同时使用
UUID作为 id(不是:id: \.self)吗? - 我能否使 ForEach-Loop 中的项目如此可识别,以便在删除它们的同时使用
ForEach(0..<users.names.count, id: \.self)时不会出现视觉错误?
【问题讨论】:
标签: swift binding swiftui swiftui-list observableobject