Slider is a control for selecting a value from a bounded linear range of values. A slider consists of a “thumb” image that the user moves between two extremes of a linear “track”. The ends of the track represent the minimum and maximum possible values. As the user moves the thumb, the slider updates its bound value.
We will start with simple example. Our view will have a text and its font will be controlled by the slider as shown below:
struct SliderExample: View {
@State private var size: CGFloat = 0.1
var body: some View {
VStack {
Text("DevTechie")
.font(.system(size: size * 50))
Slider(value: $size)
}
.padding()
}
}
Note: default range for slider is between 0.0 and 1.0, which is why we are multiplying size by 50 in font modifier so we can see Text grow/shrink in a visible size. Also note that if size becomes 0 for slider’s minimum value, Text view assumes the default value for font.
We can use parameter called in to provide minimum and maximum values for the slider. In this case, we are using this parameter to tell the slider view that font can be at least 12 points in size or at most 50 points.
struct SliderExample: View {
@State private var size: CGFloat = 12.0
var body: some View {
VStack {
Text("DevTechie")
.font(.system(size: size))
Slider(value: $size, in: 12.0...50.0)
}
.padding()
}
}
Slider has step parameter to provide increment amount. For our example, we will updated to only increment by 5:
struct SliderExample: View {
@State private var size: CGFloat = 10
var body: some View {
VStack {
Text("DevTechie")
.font(.system(size: size))
Slider(value: $size, in: 10...50, step: 5)
}
.padding()
}
}
We can add custom labels for minimum and maximum values:
struct SliderExample: View {
@State private var size: CGFloat = 10
var body: some View {
VStack {
Text("DevTechie")
.font(.system(size: size))
Slider(value: $size, in: 10...50, step: 5, minimumValueLabel: Image(systemName: "heart"), maximumValueLabel: Image(systemName: "heart.fill"), label: {})
}
.padding()
}
}
With that we have reached the end of this article. Thank you once again for reading. Subscribe our weekly newsletter at https://www.devtechie.com