SwiftUI如何使用滑动功能禁用行删除?

问题描述 投票:0回答:1

我正在通过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)
    }
}
swiftui
1个回答
0
投票

您可以使用.deleteDisabled(_ isDisabled:)修饰符。但是您必须考虑到此修饰符的返回类型是View,而不是Text。因此实施起来有点复杂。您可以使用以下示例:

  1. 创建这样的CellView
struct CellView: View {
    var title: String
    var isDeletable: Bool

    var body: some View {
        return Text(title).deleteDisabled(!isDeletable)
    }
}

您可以使用VStackHStack等来设计单元格,但是您应该考虑在此层次结构的父级上使用此修饰符。如下图所示:

var body: some View {
    HStack {
        VStack {
            ZStack {
                ...
            }
        }
    }
    .deleteDisabled(!isDeletable)
}
  1. 之后,您可以像下面这样在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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.