Skip to content

Instantly share code, notes, and snippets.

@christianselig
Created February 12, 2024 20:26
Show Gist options
  • Save christianselig/eda075422436f4e4934565da001455d4 to your computer and use it in GitHub Desktop.
Save christianselig/eda075422436f4e4934565da001455d4 to your computer and use it in GitHub Desktop.
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
}
)
}
}
@lightandshadow68
Copy link

lightandshadow68 commented Feb 12, 2024

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