0
0
iOS Swiftmobile~5 mins

Toggle switch in iOS Swift

Choose your learning style9 modes available
Introduction

A toggle switch lets users turn something on or off easily. It is like a light switch in your home.

To let users enable or disable notifications in an app.
To turn on or off dark mode in settings.
To activate or deactivate location services.
To switch between sound on and silent mode.
To control privacy settings like sharing location.
Syntax
iOS Swift
let toggleSwitch = UISwitch()
toggleSwitch.isOn = true
// Add target for value change
toggleSwitch.addTarget(self, action: #selector(switchChanged), for: .valueChanged)

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

Use isOn property to set or get the switch state.

Use addTarget(_:action:for:) to handle user toggling the switch.

Examples
This creates a switch that starts in the OFF position.
iOS Swift
let toggleSwitch = UISwitch()
toggleSwitch.isOn = false
This sets up a function to run when the user changes the switch.
iOS Swift
toggleSwitch.addTarget(self, action: #selector(switchChanged), for: .valueChanged)
This function prints the current state of the switch when toggled.
iOS Swift
@objc func switchChanged(_ sender: UISwitch) {
    print("Switch state is \(sender.isOn ? "ON" : "OFF")")
}
Sample App

This app shows a toggle switch in the center of the screen. When you flip it, the app prints "Switch is ON" or "Switch is OFF" in the console.

iOS Swift
import UIKit

class ViewController: UIViewController {
    let toggleSwitch = UISwitch()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        toggleSwitch.isOn = false
        toggleSwitch.translatesAutoresizingMaskIntoConstraints = false
        toggleSwitch.addTarget(self, action: #selector(switchChanged), for: .valueChanged)

        view.addSubview(toggleSwitch)

        NSLayoutConstraint.activate([
            toggleSwitch.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            toggleSwitch.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

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

Remember to add the switch to your view to make it visible.

Use Auto Layout constraints to position the switch nicely on screen.

The switch sends events only when the user changes it, not when you set isOn programmatically.

Summary

A toggle switch lets users turn options on or off with a simple tap.

Use UISwitch in iOS to create toggle switches.

Handle changes with addTarget and check isOn to know the state.