Created
March 23, 2020 14:28
-
-
Save alladinian/191ea9717d528f6a8140eecdc96e5969 to your computer and use it in GitHub Desktop.
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 Draggable: ViewModifier { | |
@State var isDragging: Bool = false | |
@State var offset: CGSize = .zero | |
@State var dragOffset: CGSize = .zero | |
var onChanged: ((CGSize) -> Void)? | |
var onEnded: ((CGSize) -> Void)? | |
func body(content: Content) -> some View { | |
let drag = DragGesture() | |
.onChanged { (value) in | |
self.offset = self.dragOffset + value.translation | |
self.isDragging = true | |
self.onChanged?(self.offset) | |
}.onEnded { (value) in | |
self.isDragging = false | |
self.offset = self.dragOffset + value.translation | |
self.dragOffset = self.offset | |
self.onEnded?(self.offset) | |
} | |
return content.offset(offset).gesture(drag) | |
} | |
} | |
extension View { | |
func draggable(onChanged: ((CGSize) -> Void)? = nil, onEnded: ((CGSize) -> Void)? = nil) -> some View { | |
return self.modifier(Draggable(onChanged: onChanged, onEnded: onEnded)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment