3

在编辑模式下如何删除 SwiftUI 列表行中的删除按钮?请注意,允许对行重新排序的行右侧的汉堡包按钮需要继续起作用。

背景 - 想要一个始终启用“重新排序”行功能的列表。编辑模式似乎可以启用此功能(即在编辑模式下保留列表),但不希望每行都有红色的删除按钮。

这是一个 SwiftUI 特定的问题。

编辑:仅在此处删除删除按钮后,滑动删除仍然有效...

4

2 回答 2

6

有一个修饰符,只需添加'.deleteDisabled(true)'。您还可以将变量传递给它,从而有条件地禁用删除。

于 2019-11-07T07:42:20.477 回答
1

Xcode 11.2, Swift 5.1 只是不在 List 中提供 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!)
    }
}
于 2019-11-07T06:03:08.597 回答