Created
February 12, 2024 20:26
-
-
Save christianselig/eda075422436f4e4934565da001455d4 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
import SwiftUI | |
struct ContentView: View { | |
var body: some View { | |
Slidey() | |
} | |
} | |
struct Slidey: View { | |
let width: CGFloat = 200.0 | |
@State var progress = 0.5 | |
@State var isGestureActive = false | |
var body: some View { | |
Capsule() | |
.foregroundStyle(Color.black) | |
.overlay(alignment: .leading) { | |
Capsule() | |
.foregroundStyle(Color.green) | |
.frame(width: width * progress) | |
} | |
.frame(width: width, height: isGestureActive ? 40.0 : 20.0) | |
.animation(.default, value: isGestureActive) | |
.gesture(DragGesture() | |
.onChanged { value in | |
if !isGestureActive { | |
isGestureActive = true | |
} | |
progress = value.location.x / width | |
} | |
.onEnded { value in | |
isGestureActive = false | |
} | |
) | |
} | |
} |
Edit: With Masking
struct Slidey: View {
@State var size: CGSize = CGSize(width: 200, height: 20)
@State var progress = 0.5
@GestureState private var isGestureActive: Bool = false
var body: some View {
Capsule()
.foregroundStyle(Color.black)
.overlay(alignment: .leading) {
Capsule()
.foregroundStyle(Color.green)
.mask(alignment: .leading) {
let cappedWidth = max(size.width * progress, .zero)
Capsule()
.frame(width: cappedWidth)
}
}
.frame(width: size.width, height: size.height)
.gesture(DragGesture(minimumDistance: 0)
.updating($isGestureActive, body: { _, out, _ in
out = true
})
.onChanged { value in
progress = value.location.x / size.width
}
)
.onChange(of: isGestureActive) { oldValue, newValue in
withAnimation(.default) { size.height = newValue ? 40 : 20 }
}
}
}
You probably want this in a clipShape anyway to handle the slider getting flattened at the beginning.
struct Slidey: View {
let width: CGFloat = 200.0
@State var progress = 0.5
@State var isGestureActive = false
var body: some View {
ZStack(alignment: .leading) {
Capsule()
.foregroundStyle(Color.black)
Capsule()
.foregroundStyle(Color.green)
.frame(width: width * progress)
}
.gesture(DragGesture()
.onChanged { value in
if !isGestureActive {
isGestureActive = true
}
progress = min(1.0, value.location.x / width)
}
.onEnded { value in
isGestureActive = false
}
)
.clipShape(
Capsule()
)
.frame(width: width, height: isGestureActive ? 40.0 : 20.0)
.animation(.default, value: isGestureActive)
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Edit