Skip to content

Instantly share code, notes, and snippets.

@marktrobinson
Last active June 4, 2021 05:35
Show Gist options
  • Save marktrobinson/1aff96db242ef9174a3804c20c56d0eb to your computer and use it in GitHub Desktop.
Save marktrobinson/1aff96db242ef9174a3804c20c56d0eb to your computer and use it in GitHub Desktop.
DragAndDrop (Not working on macOS)
import SwiftUI
import UniformTypeIdentifiers
struct Square: View {
let id: String
let fillColor: Color
var body: some View {
Rectangle()
.fill(fillColor)
.frame(width: 100, height: 100)
.onDrag({ NSItemProvider(object: id as NSString) })
}
}
struct DropSquare: View {
@State private var fillColor: Color = .gray
var body: some View {
Rectangle()
.fill(fillColor)
.frame(width: 100, height: 100)
.onDrop(
of: [.text],
delegate: DroppyMcDrop(fillColor: $fillColor)
)
}
}
struct DroppyMcDrop: DropDelegate {
@Binding var fillColor: Color
func performDrop(info: DropInfo) -> Bool {
guard info.hasItemsConforming(to: [.text]),
let itemProvider = info.itemProviders(for: [.text]).first else {
return false
}
_ = itemProvider.loadObject(ofClass: String.self) { item, error in
guard error == nil else {
print(error!)
return
}
print(item)
}
return true
}
}
struct DragAndDrop: View {
var body: some View {
VStack {
HStack {
VStack {
Square(id: "red", fillColor: .red)
Square(id: "blue", fillColor: .blue)
}
VStack {
Square(id: "green", fillColor: .green)
Square(id: "yellow", fillColor: .yellow)
}
}
HStack {
VStack {
DropSquare()
DropSquare()
}
VStack {
DropSquare()
DropSquare()
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
DragAndDrop()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment