SwiftUI: Bedingt onDelete
Oct 06 2020
Ich versuche, eine Liste zu erstellen, die Benutzer nur nach dem Aufrufen eines Bearbeitungsmodus löschen können. Ich habe versucht, die ternäre Operation im Modifikator onDelete zu verwenden, konnte dies jedoch nicht herausfinden. Irgendwelche Empfehlungen?
Hier ist mein Code:
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)
}
}
Antworten
1 Asperi Oct 06 2020 at 00:48
Ich gehe davon aus, dass Sie Folgendes suchen
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 !!
}
}
DimNovo Oct 06 2020 at 01:08
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)
}
}