UISlider With Fixed Increments For Filtering in Swift

This post illustrates a solution for using a UISlider with fixed increments to provide a filtering mechanism in Swift, and comes complete with a sample app. If you want to jump to the app, the link is at the end of this post.

The project is setup to offer the user a slider to filter precious metals, with categories of Silver, Gold, and All. To illustrate hooking into the slider to update a filter, this app will display the relevant picture corresponding to the chosen filter. A real app might be making REST requests to a server somewhere, or it could be filtering local data already retrieved.

The ViewController in the Storyboard is configured to have the slider with a minimum of 0, maximum of 10, and an initial value of 5, which starts the slider in the middle.

In code we will want to handle the slider movement such that it can only be one of those 3 values, and of course that means the values are based on an even increment of 5 in this case. We could just as easily have more possible slider stops, and then the increment value would change.

This ViewController class for this project is shown below.

The FilterMode enum defines the possible values for the slider. Changes to the slider are handled in sliderChanged. There are two parts to the code in this method. First, the value that the slider is being stopped at is used along with the increment of 5 to determine whether the slider is closest to 0, 5, or 10. The slider is then set to the fixed increment that it was closest to.

The second part of the sliderChanged is just illustrating how filtering can be triggered from the slider. In this sample app, handleFilter is called to load an image based on the current FilterMode as derived from the slider.

I used this kind of filtering technique in a commercial app that was using Google Maps and Google Places, to allow the user to filter the returned places based on other criteria specific to the app. Of course there are other UI controls that could be used instead where more flexibility is required. However, when there is one major filtering mechanism to be applied, and the customer really wants a slider, then a slider it is!

You can download and run the sample app from here on GitHub.

Leave a Comment: