Last active
April 5, 2023 16:24
-
-
Save ohayon/83305d9c48e4fc3e7c3851ba10ddc4c9 to your computer and use it in GitHub Desktop.
Example of making a reusable `draggable()` modifier for SwiftUI Views
This file contains hidden or 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
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
Fixed it but you'll have to use Throttler