Skip to content

Instantly share code, notes, and snippets.

@juandahurt
Last active March 10, 2021 14:50
Show Gist options
  • Save juandahurt/0d970d578d06551fcfbd3c408c2e47df to your computer and use it in GitHub Desktop.
Save juandahurt/0d970d578d06551fcfbd3c408c2e47df to your computer and use it in GitHub Desktop.
Drag and drop in SwiftUI
import SwiftUI
struct DraggableView<Content>: View where Content: View {
var onDrop: () -> Void
var content: Content
@State private var offset: CGSize = .zero
init(onDrop: @escaping () -> Void, content: @escaping () -> Content) {
self.onDrop = onDrop
self.content = content()
}
var body: some View {
content
.offset(offset)
.gesture(
DragGesture()
.onChanged { value in
offset = value.translation
}
.onEnded { _ in
offset = .zero
onDrop()
}
)
}
}
struct ContentView: View {
var body: some View {
DraggableView(onDrop: self.onDrop) {
Text("Drag me!")
}
}
func onDrop() {
print("the view has been dropped.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment