Create UISwitch in Swift Programmatically

This short examples demonstrates how to:

  • Create UISwitch in Swift programmatically
  • How to position UISwitch on a view
  • How to set UISwitch state to On and Off
  • How to call a your custom function when UISwitch state changes
import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.
        let switchDemo=UISwitch(frame:CGRect(x: 150, y: 150, width: 0, height: 0))
        switchDemo.addTarget(self, action: #selector(ViewController.switchStateDidChange(_:)), for: .valueChanged)
        switchDemo.setOn(true, animated: false)
    func switchStateDidChange(_ sender:UISwitch!)
        if (sender.isOn == true){
            print("UISwitch state is now ON")
            print("UISwitch state is now Off")
    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

Have a look at this Video blog post of mine in which I demonstrate how to create UISwitch in Swift using Mainstoryboard:

UISwitch example with 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