UISlider Tutorial in iOS8 with Swift

A Slider object is a visual control used to select a single value from a continuous range of values. Sliders are always displayed as horizontal bars. An indicator, or thumb, notes the current value of the slider and can be moved by the user to change the setting. In this tutorial, we display an UISlider and a Label. When moving the slider, the corresponding value will be displayed in the Label.

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftSliderTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard. In Xcode 6 view controllers are now square by default, so that you can create one user interface use just for multiple devices. In iOS8 you can layout the storyboard using constraints and size classes. Since this app is only going to be for the iPhone, you can disable size classes. In the File Inspector untick Use Size Classes.

Choose Keep size class data for: iPhone, and click Disable Size Classes.

Drag a Slider to the main view and span its width to the width of the main View. Select the slider and go to the Attributes inspector. Under the slider section change the maximum value to 100 and change the current value to 0.

The thumb of the slider will move to the left side indicating the current value of 0. Next, drag a label to the main view and position it below the slider. Center the text and change it to 0. The Storyboard will look like this.

Select the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl and drag from the Slider to the ViewController class and create the following outlet.

Ctrl and drag from the Label to the Viewcontroller class and create the following outlet.

Finally, Ctrl and Drag from the Slider to the ViewController class and create the following action.

Go to the ViewController.swift file and implement the sliderValueChanged Action method

@IBAction func sliderValueChanged(sender: UISlider) {
  var currentValue = Int(sender.value)
  label.text = "\(currentValue)"

The slider's sender.value is a float variable so we cast it to an integer. Build and Run the project and move the slider to update the value of the label.

You can download the source code of the iOS8SwiftSliderTutorial at the ioscreator repository on github.