Last active
March 10, 2021 14:50
-
-
Save juandahurt/0d970d578d06551fcfbd3c408c2e47df to your computer and use it in GitHub Desktop.
Drag and drop in SwiftUI
This file contains 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 | |
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