在 SwiftUI 中的列表上实现删除功能
Implementing a delete feature on a list in SwiftUI
我按照 this document (and this one) 使用 SwiftUI
将 删除 功能添加到我的应用列表中。两个页面都说,一旦你添加了 .onDelete(perform: ...) 一段代码,你就可以滑动并获得 Delete按钮。然而这不是我所看到的。代码可以编译,但我在滑动时什么也看不到。
我的列表由这样的代码备份:
@FetchRequest(
entity: ...,
sortDescriptors: []
) var myList: FetchedResults<MyEntity>
而不是 @State。这可能是个问题吗?
下面是更多相关代码,如果这可能有用:
private func deleteSpot(at index: IndexSet) {
print(#function)
}
.........
var body: some View {
VStack {
ForEach(self.myList, id: \.self.name) { item in
HStack {
Spacer()
Button(action: {
self.showingDestinList.toggle()
.....
UserDefaults.standard.set(item.name!, forKey: "LocSpot")
}) {
item.name.map(Text.init)
.font(.largeTitle)
.foregroundColor(.secondary)
}
Spacer()
}
}.onDelete(perform: deleteSpot)
}
动态容器的 滑动删除 仅在 List
中有效,因此制作
var body: some View {
List { // << here !!
ForEach(self.myList, id: \.self.name) { item in
HStack {
// ... other code
}
}.onDelete(perform: deleteSpot)
}
}
通过搜索和尝试各种选项,我最终找到了问题所在。
我觉得解决方案有点荒谬,但为了避免其他人浪费时间,这里是:
post 中代码的最后一部分需要像下面这样修改才能工作。
var body: some View {
VStack {
List {
ForEach(self.myList, id: \.self.name) { item in
HStack {
Spacer()
Button(action: {
self.showingDestinList.toggle()
.....
UserDefaults.standard.set(item.name!, forKey: "LocSpot")
}) {
item.name.map(Text.init)
.font(.largeTitle)
.foregroundColor(.secondary)
}
Spacer()
}
}.onDelete(perform: deleteSpot)
}
}
我按照 this document (and this one) 使用 SwiftUI
将 删除 功能添加到我的应用列表中。两个页面都说,一旦你添加了 .onDelete(perform: ...) 一段代码,你就可以滑动并获得 Delete按钮。然而这不是我所看到的。代码可以编译,但我在滑动时什么也看不到。
我的列表由这样的代码备份:
@FetchRequest(
entity: ...,
sortDescriptors: []
) var myList: FetchedResults<MyEntity>
而不是 @State。这可能是个问题吗?
下面是更多相关代码,如果这可能有用:
private func deleteSpot(at index: IndexSet) {
print(#function)
}
.........
var body: some View {
VStack {
ForEach(self.myList, id: \.self.name) { item in
HStack {
Spacer()
Button(action: {
self.showingDestinList.toggle()
.....
UserDefaults.standard.set(item.name!, forKey: "LocSpot")
}) {
item.name.map(Text.init)
.font(.largeTitle)
.foregroundColor(.secondary)
}
Spacer()
}
}.onDelete(perform: deleteSpot)
}
动态容器的 滑动删除 仅在 List
中有效,因此制作
var body: some View {
List { // << here !!
ForEach(self.myList, id: \.self.name) { item in
HStack {
// ... other code
}
}.onDelete(perform: deleteSpot)
}
}
通过搜索和尝试各种选项,我最终找到了问题所在。 我觉得解决方案有点荒谬,但为了避免其他人浪费时间,这里是:
post 中代码的最后一部分需要像下面这样修改才能工作。
var body: some View {
VStack {
List {
ForEach(self.myList, id: \.self.name) { item in
HStack {
Spacer()
Button(action: {
self.showingDestinList.toggle()
.....
UserDefaults.standard.set(item.name!, forKey: "LocSpot")
}) {
item.name.map(Text.init)
.font(.largeTitle)
.foregroundColor(.secondary)
}
Spacer()
}
}.onDelete(perform: deleteSpot)
}
}