Today I will show you how to use Slider.
The Slider is very easy to use. Users can quickly set the value by dragging the slider within the range of the minimum value and maximum values range. It is often used for player volume adjustment, progress adjustment, camera zooming, etc.
Knowledge points:
First, add a property of type Double and set its initial value to 0.
This property has a @State property wrapper, which means that the property will be data-bound to the Slider.
@State var progress: Double = 0
Next:
Add a Slider and bind it to the progress property.
Then, when the user adjusts the Slider, the value of this property will also change synchronously.
Slider(value: $progress)
Next:
Add a Text to display the value of progress in real-time.
Text("progress: \(progress)")
Next:
Add another Slider and set its data range to -5 to 5
Slider(value: $progress, in: -5...5)
Next:
Add a trailing closure and print logs in the code block to show whether to start or stop dragging the Slider.
Then, run the app and check the logs.
Slider(value: $progress, in: -5...5) { item in
print("is dragging: \(item)")
}
Next:
Add another Slider.
Add an HStack as a container for subviews.
Add an Image to each end of the Slider.
Set the Slider value range from 0 to 100.
Set the Slider step to 2.
Sets the color of the Slider and inverts its color.
HStack {
Image(systemName: "speaker.wave.1.fill")
Slider(value: $progress, in: 0...100, step: 2) { item in
print("is dragging: \(item)")
}
.accentColor(.red).colorInvert()
Image(systemName: "speaker.wave.3.fill")
}
Source Code:
struct ContentView: View {
@State var progress: Double = 0
var body: some View {
VStack {
Slider(value: $progress)
Slider(value: $progress, in: -5...5) { item in
print("is dragging: \(item)")
}
HStack {
Image(systemName: "speaker.wave.1.fill")
Slider(value: $progress, in: 0...100, step: 2) { item in
print("is dragging: \(item)")
}
.accentColor(.red).colorInvert()
Image(systemName: "speaker.wave.3.fill")
}
Text("progress: \(progress)")
}
.padding()
}
}
Follow me on:
Commentaires