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.
3
Answers
First you need to read the width of your
Slider
, for that you’re gonna need aGeometryReader
. using the current value of theSlider
, you can approximate the position of the thumb. Then you offset yourText
: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
Test module on GitHub
I have tried
@Asperi
Answer and He did very well, just few updates required:Problems:
Updated Code:
Usage: