How To Use iOS UISwitch In Interface Builder And Programmatically In Swift Example

This example will tell you how to create and use UISwitch component both in Xcode interface builder and swift source code. It will add one label, one UISwitch in Main.storyboard. And the other UISwitch component is created and used in ViewController.swift file use source code programmatically. Let us first look at the example demo as below.

ios uiswitch example

1. iOS UISwitch Example Creation Steps.

  1. Create a Xcode project use Single View App template. Below is the project files list.
    ios uiswitch example project files list
  2. Click to edit the Main.storyboard file, add one label and one UISwitch ui component in it ( How To Display Xcode Library, Assistant Editor, Inspectors Window ). And add constraints to them to make them auto layout responsively ( How To Add Constraints In Xcode 10 To Implement Auto Layout, iOS Auto Layout With Constraint Example ).
  3. Connect the label and UISwitch ui component to the ViewController class’s @IBOutlet instance variables, and add a @IBAction function to process the UISwitch value changed event ( How To Connect Storyboard UI Component To ViewController Class Code ).
  4. Then write below source code in the ViewController.swift class file to create the second UISwitch object programmatically. See below code to know how to create the second UISwitch ui component programmatically.
    //
    //  ViewController.swift
    //  iOSUISwitchExample
    //
    //  Created by song zhao on 11/11/19.
    //  Copyright © 2019 dev2qa.com. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController {
        
        // This UISwitch object is create programmatically in source code.
        var switch1 : UISwitch!
    
        // Reference to the test label.
        @IBOutlet weak var label: UILabel!
        
        // Reference to the UISwitch in Main.storyboard.
        @IBOutlet weak var `switch`: UISwitch!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            // Get the first UISwitch object's x, y location value.
            let switch0Frame: CGRect = `switch`.frame
            let switch0Y: CGFloat = switch0Frame.origin.y
            let switch0X:CGFloat = switch0Frame.origin.x
            
            // Create the second UISwitch object.
            switch1 = UISwitch()
            
            // Set the second UISwitch object's x, y location value. The second UISwitch is located below the first one.
            switch1.frame.origin = CGPoint(x: switch0X, y:switch0Y + 50)
            
            // The second UISwitch is turned on by default.
            switch1.setOn(true, animated: true)
            
            // Register a function to process second UISwitch's value changed event.
            switch1.addTarget(self, action: #selector(turnSecondSwitch), for: UIControl.Event.valueChanged)
            
            // Add the second UISwitch to the screen root view.
            self.view.addSubview(switch1)
            
        }
    
        // This function will be invoked when the first UISwitch component is pressed.
        @IBAction func turnSwitch(_ sender: UISwitch) {
            
            // Get first UISwitch current status.
            let switchStatus:Bool = sender.isOn
            
            // Change the label text and second UISwitch status accordingly.
            if(switchStatus){
                label.text = "First switch is turned on"
                
                switch1.setOn(false, animated: true)
            }else{
                label.text = "First switch is turned off"
                
                switch1.setOn(true, animated: true)
            }
            
        }
        
        // This function will be called when user turn on/off the second UISwitch object.
        @objc func turnSecondSwitch(srcObj: UISwitch){
            
            // Get second UISwitch current status.
            let switchStatus:Bool = srcObj.isOn
            
            // Change the label text and first UISwitch status accordingly.
            if(switchStatus){
                label.text = "Second switch is turned on"
                
                `switch`.setOn(false, animated: true)
            }else{
                label.text = "Second switch is turned off"
                
                `switch`.setOn(true, animated: true)
            }
            
        }
        
    }
    
    
READ :   How To Change Swift Constraints To Make Autolayout Programmatically

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.