Skip to content

Instantly share code, notes, and snippets.

@darrarski
Created February 11, 2022 23:41
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 darrarski/b67ca3726c6c651e0226671d5c1bb71d to your computer and use it in GitHub Desktop.
Save darrarski/b67ca3726c6c651e0226671d5c1bb71d to your computer and use it in GitHub Desktop.
SwiftUI workaround for broken animation when deleting collection item with context menu.
import SwiftUI
struct Item: Equatable, Identifiable {
var id = UUID()
var color: Color
}
struct ContentView: View {
@State var items = Array(repeating: [Color.red, .green, .blue], count: 10)
.flatMap { $0 }
.map { Item(color: $0) }
var body: some View {
ScrollView {
LazyVGrid(
columns: [
GridItem(
.adaptive(minimum: 64, maximum: 128),
spacing: 10
)
],
alignment: .leading,
spacing: 10,
content: {
ForEach(items) { item in
ItemView(item: item)
.contextMenu {
Button(
role: .destructive,
action: {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
withAnimation {
items.removeAll(where: { $0.id == item.id })
}
}
},
label: {
Label("Delete", systemImage: "trash")
}
)
}
}
}
)
.padding(10)
}
}
}
struct ItemView: View {
var item: Item
var body: some View {
RoundedRectangle(
cornerRadius: 10,
style: .continuous
)
.fill(item.color)
.aspectRatio(1, contentMode: .fill)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment