Create UISlider Programmatically in Swift

In this short Swift code example, you will learn how to create a UISlider Programmatically. The code example below will cover the following:

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

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

import UIKit
class ViewController: UIViewController {
    
    let step:Float=10 // If you want UISlider to snap to steps by 10
    
    override func viewDidLoad()
    {
        super.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 = UIColor.green
        mySlider.addTarget(self, action: #selector(self.sliderValueDidChange(_:)), for: .valueChanged)
        
        self.view.addSubview(mySlider)
        
    }
    
    @objc 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() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published. Required fields are marked *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!