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

How to Make a Freaking iPhone App - iOS 10 and Swift 3
icon icon

iOS 10 & Swift 3: From Beginner to Paid Professional

The Complete iOS 10 Developer Course - Build 21 Apps

Swift 3 - Learn to Code with Apple's New Language
icon icon

Learn How to Build Mobile Apps for iOS with Swift, PHP and MySQL
icon icon

Follow me on one of your favourite social networks to learn about new video tutorials and code examples:

Twitter: @SwiftVideoBlog
Google Plus:
Facebook: Swift Developer Blog on Facebook