Skip to content

Instantly share code, notes, and snippets.

@brunogb
Last active July 1, 2020 17:44
Show Gist options
  • Save brunogb/5a2c63cbf2ab2a9d2cfc3b40969479fb to your computer and use it in GitHub Desktop.
Save brunogb/5a2c63cbf2ab2a9d2cfc3b40969479fb to your computer and use it in GitHub Desktop.
Drag'n'Drop with SwiftUI
import SwiftUI
import PlaygroundSupport
struct MyView: View {
@State var viewOffset: CGSize = .zero {
didSet {
let newFrame = viewFrame.offsetBy(dx: self.viewOffset.width, dy: self.viewOffset.height)
self.canDrop = containerFrame.intersects(newFrame)
}
}
@State var containerFrame: CGRect = .zero
@State var viewFrame: CGRect = .zero {
didSet {
print("View frame: \(self.viewFrame)")
}
}
@State var canDrop: Bool = false
var body: some View {
VStack {
VStack {
Text( canDrop ? "Drop view here": "You cant drop here")
}
.background(canDrop ? Color.yellow : Color.blue)
.overlay(GeometryReader { r in
Color.clear
.onAppear {
self.containerFrame = r.frame(in: .global)
print("\(self.containerFrame)")
}
})
HStack {
Text("Drag me")
}
.overlay(GeometryReader { r in
Color.clear
.onAppear {
self.viewFrame = r.frame(in: .global)
}
})
.background(Color.white)
.offset(viewOffset)
.gesture(DragGesture(coordinateSpace: .global).onChanged({ (value) in
self.viewOffset = value.translation
}).onEnded({ (value) in
self.viewOffset = .zero
}))
}
}
}
let controller = UIHostingController(rootView: MyView())
PlaygroundPage.current.liveView = controller
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment