iOS UISlider With Examples

In this tutorial, we’ll be discussing and implementing the UISlider in our iOS Application.

UISlider

A UISlider is a control that allows the user to select a value from a range of values horizontally by dragging the thumb to the position desired.

Some use cases where a UISlider is used:

  • Changing the Volume
  • Changing the Brightness
  • Changing the current seek of the Video

To create a new UISlider UI in your application, most importantly you need to specify the range of values.
The isContinous property is used to set whether the slider is continous through the range of values or not.

That means, when the isContinous is set to false, the value change would be notified to the target action method only when you release the thumb.

We can set UIImage at either end of the UISlider.

  • minimumValueImage and maximumValueImage are used to set the image at either end.
  • minimumTrackTintColor is used to set the color of the track till the thumb’s current position.
  • maximumTrackTintColor is used to set the color of the track from the current thumb position till the end of the track.
  • thumbTintColor is used to set the tint color property on the thumb of the UISlider
  • currentThumbImage is used to set the image to be rendered on the thumb.
  • setThumbImage is used to set the image for a specific event.

Accessing the Values

To access the value of the UISlider we can do the following:

  • var value: Float: The slider’s current value.
  • func setValue(Float, animated: Bool): Sets the slider’s current value, allowing you to animate the change visually.
  • minimumValue maximumValue is used to get and set the min and max values in Float for the UISlider.

In the following section, we’ll be creating UISlider. Both programmatically and using the Interface Builder in our Storyboard.

Let’s get started!

Project Storyboard

The Main.storyboard of our XCode project looks like this:

ios-uislider-main-storyboard

 

The IBAction for the event type Value changed can be created as:

ios-uislider-main-storyboard

 

Code

The code for the ViewController.swift is given below:

In the above code, we’ve added a programmatically created UISlider at the top of our layout.
We’ve set the UIImage from the Assets folder.

To differentiate between the two UISliders we’ve set a tag on one of them.
The value displayed on the Label would be of the type.

The output of the application in action is given below:

ios uislider output

The values are displayed as a Float.

In order to make them snap to an integer, we can do the following in our above Swift class.

The output now looks like:

ios uislider output 2

That brings an end to this tutorial. You can download the project from the link below:

By admin

Leave a Reply

%d bloggers like this: