UISwitch in UIKIt

UISwitch is a simple yet powerful component in the UIKit framework, providing a user interface element that allows users to toggle between on and off states.

article

UISwitch in UIKit


UISwitch is a simple yet powerful component in the UIKit framework, providing a user interface element that allows users to toggle between on and off states. In this article, we will explore what UISwitches are, the various functionalities they offer, and provide practical code examples to demonstrate how you can implement and customize them in your iOS projects.


What is a UISwitch?


A UISwitch is a UIControl that provides a binary choice to the user, typically represented as an on/off switch. It is commonly used for enabling or disabling settings, features, or other binary options within an app. When the switch is toggled, it sends a value change event to its target-action mechanism, allowing the app to respond accordingly.


What Can You Do with UISwitches?


UISwitches offer a range of functionalities and customization options. Here are some key things you can do with UISwitches:


  • Toggle States: Allow users to switch between on and off states.
  • Custom Actions: Respond to state changes using target-action methods.
  • Custom Appearance: Customize the appearance of the switch, including its tint color, on tint color, and thumb tint color.
  • Enabled/Disabled State: Enable or disable the switch based on specific conditions.

Implementing UISwitch in Swift


Let's dive into some code examples to see how you can create, customize, and work with UISwitches in Swift.


To create a simple UISwitch, you need to initialize it and add it to your view. Here is an example:


import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Create a UISwitch
        let mySwitch = UISwitch()
        mySwitch.center = view.center
        mySwitch.addTarget(self, action: #selector(switchToggled(_:)), for: .valueChanged)
        
        // Add the switch to the view
        view.addSubview(mySwitch)
    }

    @objc func switchToggled(_ sender: UISwitch) {
        if sender.isOn {
            print("Switch is ON")
        } else {
            print("Switch is OFF")
        }
    }
}

In this example, we create a UISwitch and position it at the center of the view. We also add a target-action method to handle the switch's value changes. The switchToggled method prints the current state of the switch to the console.


Customizing UISwitch Appearance


You can customize the appearance of UISwitch to match the design of your application. Here is an example of customizing the tint color, on tint color, and thumb tint color:


import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Create a UISwitch
        let mySwitch = UISwitch()
        mySwitch.center = view.center
        mySwitch.addTarget(self, action: #selector(switchToggled(_:)), for: .valueChanged)
        
        // Customize appearance
        mySwitch.tintColor = .gray
        mySwitch.onTintColor = .green
        mySwitch.thumbTintColor = .white
        
        // Add the switch to the view
        view.addSubview(mySwitch)
    }

    @objc func switchToggled(_ sender: UISwitch) {
        if sender.isOn {
            print("Switch is ON")
        } else {
            print("Switch is OFF")
        }
    }
}

In this example, we customize the UISwitch by setting its tint color, on tint color, and thumb tint color. The tint color changes the border color of the switch when it is off, the on tint color changes the background color when the switch is on, and the thumb tint color changes the color of the thumb (the round button inside the switch).


Enabling and Disabling UISwitch


You can enable or disable the UISwitch based on specific conditions. Here is an example:


import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        // Create a UISwitch
        let mySwitch = UISwitch()
        mySwitch.center = view.center
        mySwitch.addTarget(self, action: #selector(switchToggled(_:)), for: .valueChanged)
        
        // Disable the switch initially
        mySwitch.isEnabled = false
        
        // Add the switch to the view
        view.addSubview(mySwitch)
        
        // Create a button to enable the switch
        let enableButton = UIButton(type: .system)
        enableButton.setTitle("Enable Switch", for: .normal)
        enableButton.addTarget(self, action: #selector(enableSwitch), for: .touchUpInside)
        enableButton.translatesAutoresizingMaskIntoConstraints = false
        
        // Add the button to the view
        view.addSubview(enableButton)
        
        // Set Auto Layout constraints for the button
        NSLayoutConstraint.activate([
            enableButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            enableButton.topAnchor.constraint(equalTo: mySwitch.bottomAnchor, constant: 20)
        ])
    }

    @objc func switchToggled(_ sender: UISwitch) {
        if sender.isOn {
            print("Switch is ON")
        } else {
            print("Switch is OFF")
        }
    }
    
    @objc func enableSwitch() {
        for subview in view.subviews {
            if let mySwitch = subview as? UISwitch {
                mySwitch.isEnabled = true
            }
        }
    }
}

In this example, we disable the UISwitch initially by setting its isEnabled property to false. We also create a button that, when tapped, enables the switch by setting its isEnabled property to true.


Conclusion


UISwitches are simple yet versatile components for providing binary options in your iOS applications. In this article, we've covered the basics of what UISwitches are, their various functionalities, and provided practical code examples to help you implement and customize them in your own projects. From creating simple switches to customizing their appearance and enabling/disabling them based on conditions, mastering UISwitches is essential for building intuitive and user-friendly interfaces.


Understanding and effectively utilizing UISwitches can significantly enhance your app's usability and user experience. Experiment with different UISwitch properties and techniques to create dynamic and engaging binary options in your iOS applications.

instructor

Exodai INSTRUCTOR!

Johan t'Sas

Owner and Swift developer!