Skip to content

Instantly share code, notes, and snippets.

@davelyon
Created April 27, 2020 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davelyon/6eca9cbc2f3631a417c6bf2574c4e557 to your computer and use it in GitHub Desktop.
Save davelyon/6eca9cbc2f3631a417c6bf2574c4e557 to your computer and use it in GitHub Desktop.
Demonstrates a weird bug with SwiftUI where a Section with a `isEnabled` false will allow swipe-to-delete, but not manual deletion where it should prevent both.
import SwiftUI
struct ItemView: View {
@ObservedObject var collection: ItemCollection
@ObservedObject var item: Item
var body: some View {
HStack(alignment: .firstTextBaseline) {
Text("Item: ")
Text(item.value)
}.contextMenu(menuItems: {
Button(action: {
self.collection.deleteItem(self.item)
}) {
Text("Delete")
Image(systemName: "trash")
}
})
}
}
struct ContentView: View {
@ObservedObject var collection: ItemCollection
var body: some View {
VStack {
Form {
ForEach(collection.items) { item in
ItemView(collection: self.collection, item: item)
}
.onDelete { (indexes) in
self.collection.removeItems(at: indexes)
}
// This will allow "Swipe to delete" but otherwise ignore the `contextMenu` deletion
Section {
ForEach(collection.items) { item in
ItemView(collection: self.collection, item: item)
}
.onDelete { (indexes) in
self.collection.removeItems(at: indexes)
}
}.environment(\.isEnabled, false)
}
Form {
ForEach(collection.items) { item in
ItemView(collection: self.collection, item: item)
}
.onDelete { (indexes) in
self.collection.removeItems(at: indexes)
}
}.environment(\.isEnabled, false)
}
}
}
// MARK: - Preview
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(collection: ItemCollection())
}
}
// MARK: - Data Model
class Item: ObservableObject, Identifiable {
let id = UUID()
var value: String { self.id.uuidString }
}
class ItemCollection: ObservableObject {
@Published var items: [Item] = [ Item(), Item() ]
func deleteItem(_ item: Item) {
self.objectWillChange.send()
self.items = items.filter({$0.id != item.id })
}
func removeItems(at offsets: IndexSet) {
items.remove(atOffsets: offsets)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment