Last active
January 14, 2023 21:46
-
-
Save mecid/c7026611438808acf5972ac5bdb89211 to your computer and use it in GitHub Desktop.
SwiftUI Drag and Drop example for grid items
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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