我正在通过SwiftUI使用Xcode 11.1。
我使用以下代码实现了列表删除和排序功能。
如何通过滑动来禁用行删除?
import SwiftUI
struct ContentView: View {
@State var fruits = ["Apple", "Orange", "Banana"]
var body: some View {
NavigationView {
List {
ForEach(fruits, id: \.self) { fruit in
Text(fruit)
}
.onMove(perform: move)
.onDelete(perform: delete)
}
.navigationBarItems(trailing: EditButton())
}
}
func delete(offsets: IndexSet) {
fruits.remove(atOffsets: offsets)
}
func move(source: IndexSet, destination: Int) {
fruits.move(fromOffsets: source, toOffset: destination)
}
}
答案 0 :(得分:1)
您可以使用.deleteDisabled(_ isDisabled:)
修饰符。但是您必须考虑到此修饰符的返回类型是View
,而不是Text
。因此实施起来有点复杂。
您可以使用以下示例:
CellView
:struct CellView: View {
var title: String
var isDeletable: Bool
var body: some View {
return Text(title).deleteDisabled(!isDeletable)
}
}
您可以使用VStack
,HStack
等来设计单元格,但是您应该考虑在此层次结构的父级上使用此修饰符。如下图所示:
var body: some View {
HStack {
VStack {
ZStack {
...
}
}
}
.deleteDisabled(!isDeletable)
}
ForEach
中使用它:struct ContentView: View {
@State var fruits = ["Apple", "Orange", "Banana"]
var body: some View {
NavigationView {
List {
ForEach(fruits, id: \.self) { fruit -> CellView in
if fruit == "Orange" {
return CellView(title: fruit, isDeletable: true)
} else {
return CellView(title: fruit, isDeletable: false)
}
}
.onMove(perform: move)
.onDelete(perform: delete)
}
.navigationBarItems(trailing: EditButton())
}
}
func delete(offsets: IndexSet) {
fruits.remove(atOffsets: offsets)
}
func move(source: IndexSet, destination: Int) {
fruits.move(fromOffsets: source, toOffset: destination)
}
}