SwiftUI Slider's label visibility

Viewed 2138

Under what circumstances SwiftUI Slider's label is visible? Slider inits can take label arguments, but I don't understand what this label is for?

 struct ContentView: View {
    @State private var slVal: CGFloat = -20
    var body: some View {
        Slider(value: $slVal, in: -40...40, minimumValueLabel: Text("-40"), maximumValueLabel: Text("40")) {
            Text("Invisible text") // This view is not visible 
        }
        .padding()
    }
 }

Putting Slider inside Form doesn't make label appear. I know that DatePicker's label is displayed or not depending on .labelsHidden() modifier and also on DatePickerStyle applied by .datePickerStyle() modifier. Is there something similar with Slider?

3 Answers

It is long known bug in SwiftUI.

Here is possible workaround. Prepared with Xcode 12.1 / iOS 14.1 (backward compatible with SwiftUI 1.0)

demo

struct ContentView: View {
    @State private var slVal: CGFloat = -20
    var body: some View {
        HStack {
            Text("Invisible text")
            Slider(value: $slVal, in: -40...40, minimumValueLabel: Text("-40"), maximumValueLabel: Text("40")) {
                EmptyView()
            }
        }
        .padding()
    }
}

Slightly modified version of workaround from @Asperi:

func slider<V, C>(
    value: Binding<V>,
    in bounds: ClosedRange<V> = 0...1,
    label: () -> C,
    onEditingChanged: @escaping (Bool) -> Void = { _ in }
) -> some View where V : BinaryFloatingPoint,
                     V.Stride : BinaryFloatingPoint,
                     C: View {
    HStack {
        label()
        Slider(
            value: value,
            in: bounds,
            onEditingChanged: onEditingChanged,
            label: { EmptyView() }
        )
    }
}

and usage:

slider(value: $aValue, in: -1...1, label: {
    Text("aValue")
})

According to official documentation not all slider styles show the labels, but even in those cases, SwiftUI uses the label for accessibility (for example VoiceOver).

Related