Create UISlider Programmatically in Swift

In this short Swift code example you will learn how to:

  • Create UISlider programmatically
  • Position UISlider within a UIView
  • Set UISlider minimum and maximum values
  • Change UISlider tint colour
  • Handle UISlider value changed event
  • Make UISlider sliding continuously
  • Make UISlider move in steps by 10 or making UISlider snap to specific values

import UIKit

class ViewController: UIViewController {
    let step:Float=10 // If you want UISlider to snap to steps by 10
    override func viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let mySlider = UISlider(frame:CGRect(x: 10, y: 100, width: 300, height: 20))
        mySlider.minimumValue = 0
        mySlider.maximumValue = 100
        mySlider.isContinuous = true
        mySlider.tintColor =
        mySlider.addTarget(self, action: #selector(ViewController.sliderValueDidChange(_:)), for: .valueChanged)
    func sliderValueDidChange(_ sender:UISlider!)
        print("Slider value changed")
        // Use this code below only if you want UISlider to snap to values step by step
        let roundedStepValue = round(sender.value / step) * step
        sender.value = roundedStepValue
        print("Slider step value \(Int(roundedStepValue))")
    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

Watch this video tutorial of mine to learn how to create UISlider using Main storyboard.

UISlider example in Swift

Learn iOS Development with these Video Courses

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon