Menu & Search

UISlider with steps (snapping to values) in Swift

November 16, 2015

UISlider has been around for quite a while and it’s great for a lot of use cases. What’s not natively supported is the so-called snapping to values or “steps”. This can be easily achieved with just a few lines of code.

The solution

If you already have an app set up and you’re listening to Value Changed events, do something like this:

If you’re starting off with a fresh project, read the whole setup below.

The whole setup

Firstly, we start with an empty, single view project.

Screenshot 2015-11-16 20.34.54

Then we select Main.storyboard and add a label that will display the value (so we’re sure it works) and the slider. I’ve positioned mine like this.

Screen Shot 2015-11-16 at 20.36.54

I’ve decided that my slider should go from 0 to 1000 with steps of 10. If we click on the slider and open the Attributes Inspector (⌥+⌘+4), we can set the minimum and maximum values.

Screen Shot 2015-11-16 at 20.50.37

The next part is super nice. If you’re not familiar with connecting UI elements from storyboard to code, you should check out this nice in-depth tutorial from Apple on the subject.

Now that we have everything hooked up, we can put in the magic code from above and make it work!

Note that I changed the type of sender from AnyObject to UISlider, because I’m 100% confident that the only sender that will use this function is the UISlider. So it’s ok. 🙂

If we run the app (⌘+R), we’ll see that it works as expected. Nice and simple!

For the complete source code, check out this GitHub link or download the project directly.

 

STOP LOSING TIME WITH AUTO LAYOUT!

Take part in the 5-day course with actionable tasks that will let you become a master at recognizing and solving the most common mistakes iOS developers do with Auto Layout.

Let Auto Layout become a tool you swing with your utmost confidence!

I won't send you spam, I promise. Unsubscribe at any time. Powered by ConvertKit
Hey there! You're already subscribed to my newsletter and you've hopefully gotten some useful tips and tricks when working with iOS. If you're also working with Auto Layout, make sure to check out my book called Auto Layout Fundamentals and get a 20% off for being my subscriber! https://gum.co/autolayoutfundamentals/youareawesome
Jure Zove

A lot of things but mostly a programmer who really likes fast cars. Check me out on Twitter, if you fancy.

Related article

Introducing The “How do I Auto Layout” Cheatsheet

STOP LOSING TIME WITH AUTO LAYOUT! Take part in the…

Fastest way to use Auto Layout in code

Raise your ✋ if you hate adding views and setting…

Swift Optionals Demystified

STOP LOSING TIME WITH AUTO LAYOUT! Take part in the…

  • Jan

    Just what I was looking for! So simple, thanks a lot!

Type your search keyword, and press enter to search