在编辑模式下,如何删除SwiftUI列表行中的删除按钮?请注意,该行右侧的“汉堡包”按钮需要继续起作用,该按钮允许对行进行重新排序。
背景-希望始终启用“重新排序”行功能的列表。编辑模式似乎可以启用此功能(即,将列表保留为编辑模式),但是不希望每行上有红色的删除按钮。
这是SwiftUI特有的问题。
编辑:仅在此处删除删除按钮之后,因此滑动删除操作仍然有效...
答案 0 :(得分:1)
Xcode 11.2,Swift 5.1 只是在列表中不提供onDelete,并且将没有删除按钮
这里是例子
import SwiftUI
import Combine
struct ContentView: View {
@State private var objects = ["1", "2", "3"]
var body: some View {
NavigationView {
List {
ForEach(objects, id: \.self) { object in
Text("Row \(object)")
}
.onMove(perform: relocate)
}
.navigationBarItems(trailing: EditButton())
}
}
func relocate(from source: IndexSet, to destination: Int) {
objects.move(fromOffsets: source, toOffset: destination)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
替代方法(有局限性)
struct ContentView: View {
@State private var objects = ["1", "2", "3"]
@Environment(\.editMode) var editMode
var body: some View {
// NavigationView {
VStack {
// !!! A. using NavigationView instead of VStack above does not work,
// !!! because editMode is not updated and always .inactive
// !!! B. Also it does not work in Preview, but works in run-time
EditButton()
List {
ForEach(objects, id: \.self) { object in
Text("Row \(object)")
}
.onMove(perform: relocate)
.onDelete(perform: delete)
.deleteDisabled(disableDelete)
}
// .navigationBarItems(trailing: EditButton())
}
}
var disableDelete: Bool {
if let mode = editMode?.wrappedValue, mode == .active {
return true
}
return false
}
func relocate(from source: IndexSet, to destination: Int) {
objects.move(fromOffsets: source, toOffset: destination)
}
func delete(from source: IndexSet?) {
objects.remove(atOffsets: source!)
}
}
答案 1 :(得分:1)
有一个修饰符,只需添加'.deleteDisabled(true)'。您还可以将变量传递给它,从而有条件地禁用删除。