Skip to content

Instantly share code, notes, and snippets.

@b3ll
Created September 17, 2019 01:25
Show Gist options
  • Select an option

  • Save b3ll/4d294e1451d8866117e20f63403848b9 to your computer and use it in GitHub Desktop.

Select an option

Save b3ll/4d294e1451d8866117e20f63403848b9 to your computer and use it in GitHub Desktop.
struct ADSRSliderView: View {
fileprivate struct DragGestureState {
var previousTranslationY: CGFloat?
var deltaPercentY: CGFloat = 0.0
}
let color: Color
@State var percent: CGFloat = 1.0
@GestureState fileprivate var dragGestureState: DragGestureState = DragGestureState()
var body: some View {
GeometryReader { geo in
ZStack(alignment: .bottomLeading) {
Rectangle()
.frame(minWidth: 0.0, maxWidth: .infinity, minHeight: 0.0, maxHeight: .infinity, alignment: .bottomLeading)
.background(Color.clear)
.foregroundColor(Color.clear)
Rectangle()
.foregroundColor(self.color)
.frame(height: geo.size.height * self.percent, alignment: .bottomTrailing)
}
.frame(minWidth: 0.0, maxWidth: .infinity, minHeight: 0.0, maxHeight: .infinity, alignment: .leading)
.gesture(
DragGesture(minimumDistance: 0.0)
.updating(self.$dragGestureState) { (dragGesture, dragGestureState, _) in
let deltaY: CGFloat
if dragGestureState.previousTranslationY == nil {
dragGestureState.previousTranslationY = dragGesture.translation.height
deltaY = 0.0
} else {
deltaY = -(dragGesture.translation.height - dragGestureState.previousTranslationY!)
dragGestureState.previousTranslationY = dragGesture.translation.height
}
dragGestureState.deltaPercentY = deltaY / geo.size.height
}
.onChanged { gesture in
self.percent = (self.percent + self.dragGestureState.deltaPercentY).clamped(to: 0.0...1.0)
}
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment