我正在尝试创建一个列表,该列表仅允许用户在进入编辑模式后删除。我试图在onDelete修饰符中尝试使用三元运算,但是无法弄清楚。有什么建议吗?
这是我的代码:
struct ContentView: View {
@State private var stuff = ["First", "Second", "Third"]
@State private var check = false
var body: some View {
Form {
Button(action: { check.toggle() }, label: { Text(check ? "Editing" : "Edit") })
ForEach(0..<stuff.count) { items in
Section{ Text(stuff[items]) }
}
.onDelete(perform: self.deleteItem)
}
}
private func deleteItem(at indexSet: IndexSet) {
self.stuff.remove(atOffsets: indexSet)
}
}
答案 0 :(得分:1)
我认为您正在寻找以下内容
var body: some View {
Form {
Button(action: { check.toggle() }, label: { Text(check ? "Editing" : "Edit") })
ForEach(0..<stuff.count) { items in
Section{ Text(stuff[items]) }
}
.onDelete(perform: self.deleteItem)
.deleteDisabled(!check) // << this one !!
}
}
答案 1 :(得分:0)
struct ContentView: View {
@State private
var stuff = ["First", "Second", "Third"]
var body: some View {
NavigationView {
Form {
ForEach(0..<stuff.count) { item in
Section {
Text(stuff[item])
}
}
.onDelete(
perform: delete)
}
.navigationBarItems(
trailing:
EditButton()
)
.navigationTitle("Test")
}
}
}
extension ContentView {
private func delete(at indexSet: IndexSet) {
stuff.remove(atOffsets: indexSet)
}
}