SwiftUI - Slider



Slider is also a UI control in SwiftUI which allows the user to select a value from the continuous range by dragging the given symbol in the sliding bar. The end points of the slider represent the maximum and minimum values. It is commonly used in adjusting the sound, brightness, etc. in the app.

Creating Slider in SwiftUI

In SwiftUI, we can create slider control using the pre-defined Slider view. Just like other UI controls it also requires a biding value that represents the current state of the slider and a range in between the user selects the value.

Syntax

Following is the basic slider syntax −

Slider(
   value: Binding,
   in bounds: ClosedRange,
   step: V.Stride = 1,
   onEditingChanged: @escaping (Bool) -> Void = { _ in }
) where V : BinaryFloatingPoint, V.Stride : BinaryFloatingPoint

Parameters

Following parameters are used by this view −

  • value: Represent the selected value in the given range.

  • bounds: Represent the valid range.

  • step: Represent the distance between each value.

  • onEditingChanged: Represent a closure called when the editing begins or ends.

Example 1

The following SwiftUI program creats a simple slider.

import SwiftUI

struct ContentView: View {
   @State private var input : Float = 0.0
   var body: some View {
      VStack{
         Text("Adjust Brightness")
         Slider(value: $input, in: 0...20)
      }
   }
}   
#Preview {
   ContentView()
}

Output

Slider

Example 2

The following SwiftUI program creates multiple sliders with steps. Here the first slider is set to step = 2 which means the slider will move by 2 units whereas the second slider is set to step = 1 which means the slider will move by 1 unit.

import SwiftUI
struct ContentView: View {   
   @State private var input1 : Float = 0.0
   @State private var input2 : Float = 0.0
   
   var body: some View {
      VStack{
         Text("Product Quantity")
         Slider(value: $input1, in: 1...20, step: 2)
         Text("Product Amount")
         Slider(value: $input2, in: 1...15, step: 1)
      }
   }
}
   
#Preview {
   ContentView()
}

Output

Slider

Example 3

The following SwiftUI program is used to customize the slider view. Here we display the minimum and maximum values at the end points using minimumValueLabel and maximumValueLabel. Also, change the color of the slider to green color using the tint() modifier.

import SwiftUI
struct ContentView: View {   
   @State private var input : Float = 0.0
   var body: some View {
      VStack{
         Text("Product Quantity")
         Slider(value: $input, in: 1...20, step: 2){
            Text("Slider")
         }minimumValueLabel: {
            Text("0").font(.title2)
         }maximumValueLabel: {
            Text("20").font(.title2)
         }.tint(.green)
      }
   }
}   
#Preview {
   ContentView()
}

Output

Slider
Advertisements