How to create a custom SwiftUI Slider

Share on facebook
Share on twitter
Share on pinterest

You want to create a custom SwiftUI Slider in SwiftUI? Here you go! 👇

Step 1: Add a State property to your view’s body for keeping track of the currently selected value. It should be a Float.

Step 2: Create a HStack for aligning the Slider and it’s icons horizontally.

Step 3: Initialise and modify the items. Here you can use system- or custom icons and selected a color for them.

Step 4: Insert a Slider object by initialising it with binding it to the declared State and providing it with a floating range of values that can be selected. You can modify the Slider’s color by using the .accentColor modifier.

struct ContentView: View {
    //1. Add a State for keeping track of the current selection
    @State var currentValue = 4.0
    var body: some View {
        VStack {
            //2. Create a HStack for alining the Slider and it's icons horizontally
            HStack {
                //3. Initialise and modify the items
                Image(systemName: "sun.min")
                    .frame(width: 30, height: 30)
               //4. Initalise the Slider by binding it to the State and providing it with a range of values
                Slider(value: $currentValue, in: 0.0...10.0)
                    //5. Modify the Slider's color
                Image(systemName: "sun.max")
                    .frame(width: 30, height: 30)
            Text("Current value: \(Int(currentValue))")

You just learned how a custom SwiftUI Slider can be created!

I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, make sure you check out our free SwiftUI Basics eBook and our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!

Leave a Reply

Your email address will not be published. Required fields are marked *


Covid-19 Forces you into quarantine?

Start Mastering swiftUI Today save your 33% discount