Sliders in SwiftUI

Slider.gif

Sliders are one of the most common controls I see in iOS apps. They are super useful for things like controlling volume, scrubbing through a video, etc.

In this tutorial you’ll learn how to set up a Slider that controls the corner radius of a RoundedRectangle.

Setting Up

To start with we’re going to need a state property for our corner radius, and a RoundedRectangle which is a shape struct that SwiftUI provides out of the box. Go ahead and put your rectangle into a VStack so we can add the Slider to it later.

// Add this to the top of your view struct
@State private var cornerRadius: CGFloat = 30.0

// This goes in the body
VStack {
    RoundedRectangle(cornerRadius: cornerRadius)
        .foregroundColor(.blue)
        .frame(width: 200, height: 200)
}

I went with a blue square, but feel free to give your rectangle whatever color and size you’d like. Just make sure it fits on the screen so you can see the corners!

Adding a Slider

Next up we need to add a Slider to control our cornerRadius property. Add the following just below your RoundedRectangle in the body of your View:

Slider(value: $cornerRadius, in: 0...60)
    .padding()

To instantiate a Slider you need to pass it two things: a Binding to a state property, and a range. Our Binding is to the cornerRadius property, which allows the Slider to control its value, and the range I chose was 0-60 which limits the cornerRadius min and max values.

That’s it! Run the app and you should be able to control the corner radius of your rectangle with the Slider!

Check out some other recent tutorials

Previous
Previous

How to Push a Detail View Using NavigationLink

Next
Next

Steppers in SwiftUI