Search code examples
iosswiftxcodeswiftuislider

SwiftUI: How to move Slider Value with Thumb


I want to create slider in SwiftUI with Value label.

I have write below code.

struct SliderView: View {
    @State private var speed = 50.0
    var minValue: Double = 1
    var maxValue: Double = 100
    var body: some View {
        VStack {
            Text("\(speed,specifier: "%.f")")
                .foregroundColor(.blue)

            Slider(
                value: $speed,
                in: minValue...maxValue,
                step: 1
            ) {
                Text("Speed")
            } minimumValueLabel: {
                Text("\(minValue,specifier: "%.f")")
            } maximumValueLabel: {
                Text("\(maxValue,specifier: "%.f")")
            }

        }.padding()
    }
}

But I want to move value label with slider thumb.

I am not able to find any property to set .frame for Y value.

Question:

How to move Slider Value label with Thumb and move label value with Thumb change.

enter image description here

enter image description here

enter image description here


Solution

  • The problem here is that we do not have access to nob size and positioning (which are private) and refer only to range and current value, and this leads to some misalignment between slider's nob and hover value.

    Anyway here is possible approach using alignment guide. Tuning to nob size I leave for you.

    Tested with Xcode 13.4 / iOS 15.5

    demo

    struct SliderView: View {
        @State private var speed = 50.0
    
        var minValue: Double = 1
        var maxValue: Double = 100
    
        var body: some View {
            HStack {
                Text("\(minValue,specifier: "%.f")")
                Slider(value: $speed, in: minValue...maxValue, step: 1)
                    .alignmentGuide(VerticalAlignment.center) { $0[VerticalAlignment.center]}
                    .padding(.top)
                    .overlay(GeometryReader { gp in
                        Text("\(speed,specifier: "%.f")").foregroundColor(.blue)
                            .alignmentGuide(HorizontalAlignment.leading) {
                                $0[HorizontalAlignment.leading] - (gp.size.width - $0.width) * speed / ( maxValue - minValue)
                            }
                            .frame(maxWidth: .infinity, alignment: .leading)
                    }, alignment: .top)
                Text("\(maxValue,specifier: "%.f")")
            }
            .padding()
        }
    }
    

    Test module on GitHub