Skip to content

Instantly share code, notes, and snippets.

@mecid
Last active January 14, 2023 21:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mecid/c7026611438808acf5972ac5bdb89211 to your computer and use it in GitHub Desktop.
Save mecid/c7026611438808acf5972ac5bdb89211 to your computer and use it in GitHub Desktop.
SwiftUI Drag and Drop example for grid items
import SwiftUI
extension RandomAccessCollection {
func indexed() -> Array<(offset: Int, element: Element)> {
return Array(enumerated())
}
}
struct ContentView: View {
@State private var items: [[String]] = [
["1"], ["2"], ["3"], ["4"], ["5"], ["6"], ["7"]
]
var body: some View {
ScrollView {
LazyVGrid(columns: Array(repeating: .init(), count: 7)) {
ForEach(items.indexed(), id: \.1.self) { index, array in
VStack {
ForEach(array, id: \.self) { item in
Text(item)
.frame(
minWidth: 100, maxWidth: .infinity,
minHeight: 100, maxHeight: .infinity
)
.background(Color.red)
.onDrag {
NSItemProvider(object: item as NSString)
}
.onDrop(of: ["public.utf8-plain-text"], isTargeted: nil) { provider in
guard let item = provider.first, item.canLoadObject(ofClass: NSString.self) else {
return false
}
_ = item.loadObject(ofClass: NSString.self) { reading, error in
if let string = reading as? String {
for oldIndex in items.indices {
if let itemIndex = items[oldIndex].firstIndex(of: string) {
items[oldIndex].remove(at: itemIndex)
}
}
items[index].append(string)
}
}
return true
}
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment