Skip to content

Instantly share code, notes, and snippets.

@StefKors
Forked from ohayon/DraggableView.swift
Created July 31, 2021 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StefKors/a9e1c426ffb35f8ae85f5836af8fb5ec to your computer and use it in GitHub Desktop.
Save StefKors/a9e1c426ffb35f8ae85f5836af8fb5ec to your computer and use it in GitHub Desktop.
Example of making a reusable `draggable()` modifier for SwiftUI Views
struct DraggablePita: View {
var body: some View {
Image(uiImage: UIImage(named: "pita.png")!)
.draggable() // Add the new, custom modifier to make this draggable
}
}
// Handle dragging
struct DraggableView: ViewModifier {
@State var offset = CGPoint(x: 0, y: 0)
func body(content: Content) -> some View {
content
.gesture(DragGesture(minimumDistance: 0)
.onChanged { value in
self.offset.x += value.location.x - value.startLocation.x
self.offset.y += value.location.y - value.startLocation.y
})
.offset(x: offset.x, y: offset.y)
}
}
// Wrap `draggable()` in a View extension to have a clean call site
extension View {
func draggable() -> some View {
return modifier(DraggableView())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment