Slider iOS Tutorial

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 indicates the current value of the slider and can be moved by the user to change the setting. In this tutorial, a Slider and a Label will be displayed. When moving the slider, the corresponding value will be displayed inside the Label. This tutorial is made with Xcode 9 and built for iOS 11.

Open Xcode and create a new Single View App.

For product name, use IOS11SliderTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and 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 Slider and the Label and go to the Auto Layout align button. Select the "Horizontally in Container" checkbox and click "Add 1 Constraint".

Select the Slider and select the Auto Layout "Add New Constraints" button. Pin the Button to the to and mark the width constraint. Click "Add 2 Constraints".

Select the Label and Ctrl and Drag to the slider. Select Vertical Spacing.

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.

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) {
    let 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 IOS11SliderTutorial at the ioscreator repository on Github.