Create UISwitch in Swift Programmatically

This short example demonstrates how to create a UISwitch in Swift programmatically.

The Swift code snippet below will coder the following:

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

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 {
    
    override func viewDidLoad() {
        super.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(self.switchStateDidChange(_:)), for: .valueChanged)
        switchDemo.setOn(true, animated: false)
        self.view.addSubview(switchDemo)
        
    }
    
    @objc func switchStateDidChange(_ sender:UISwitch!)
    {
        if (sender.isOn == true){
            print("UISwitch state is now ON")
        }
        else{
            print("UISwitch state is now Off")
        }
    }
    
    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!