What is UISwitch?
UISwitch
is a toggle button in UIKit that lets users switch ON/OFF settings in an iOS app. It is commonly used for dark mode toggles, notifications, sound settings, etc.
1. Creating a UISwitch
There are two ways to add a UISwitch
:
- Using Storyboard (Interface Builder)
- Programmatically in Swift
2. Adding UISwitch via Storyboard
- Open Main.storyboard in Xcode.
- Drag and drop a
UISwitch
from the Object Library onto the view. - Create an IBOutlet in
ViewController.swift
:@IBOutlet weak var mySwitch: UISwitch!
- Modify properties in
viewDidLoad()
:override func viewDidLoad() { super.viewDidLoad() mySwitch.isOn = true // Default state (ON) }
- Add an IBAction for switch state changes:
@IBAction func switchToggled(_ sender: UISwitch) { if sender.isOn { print("Switch is ON") } else { print("Switch is OFF") } }
3. Creating UISwitch Programmatically
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Create UISwitch
let mySwitch = UISwitch()
mySwitch.isOn = true // Default ON
mySwitch.onTintColor = .systemGreen // Color when ON
mySwitch.thumbTintColor = .white // Knob color
mySwitch.translatesAutoresizingMaskIntoConstraints = false
// Add target function for value change
mySwitch.addTarget(self, action: #selector(switchChanged(_:)), for: .valueChanged)
// Add to View
view.addSubview(mySwitch)
// Set Constraints
NSLayoutConstraint.activate([
mySwitch.centerXAnchor.constraint(equalTo: view.centerXAnchor),
mySwitch.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
@objc func switchChanged(_ sender: UISwitch) {
print(sender.isOn ? "Switch is ON" : "Switch is OFF")
}
}
✅ Explanation:
- Creates a
UISwitch
programmatically. - Sets default ON state and custom colors.
- Adds an event listener to detect state changes.
4. Customizing UISwitch
4.1 Changing Colors
mySwitch.onTintColor = .systemGreen // Background when ON
mySwitch.thumbTintColor = .white // Toggle knob color
mySwitch.tintColor = .gray // Background when OFF
4.2 Checking Switch State
if mySwitch.isOn {
print("Switch is ON")
} else {
print("Switch is OFF")
}
4.3 Programmatically Toggle Switch State
mySwitch.setOn(false, animated: true) // Turns OFF with animation
5. UISwitch with UserDefaults (Save State)
To remember the switch state, use UserDefaults
:
override func viewDidLoad() {
super.viewDidLoad()
let isSwitchOn = UserDefaults.standard.bool(forKey: "switchState")
mySwitch.isOn = isSwitchOn
mySwitch.addTarget(self, action: #selector(switchChanged(_:)), for: .valueChanged)
}
@objc func switchChanged(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: "switchState")
}
✅ Explanation:
- Retrieves last saved switch state on app launch.
- Saves switch state whenever it’s toggled.
6. UISwitch for Dark Mode Toggle
To switch between Light and Dark Mode:
@objc func switchChanged(_ sender: UISwitch) {
if sender.isOn {
overrideUserInterfaceStyle = .dark
} else {
overrideUserInterfaceStyle = .light
}
}
✅ This changes the app’s appearance dynamically.
7. UISwitch Example: Notification Settings
let notificationSwitch = UISwitch()
notificationSwitch.isOn = UserDefaults.standard.bool(forKey: "notificationsEnabled")
notificationSwitch.addTarget(self, action: #selector(toggleNotifications(_:)), for: .valueChanged)
@objc func toggleNotifications(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: "notificationsEnabled")
print(sender.isOn ? "Notifications Enabled" : "Notifications Disabled")
}
✅ This saves and retrieves the notification setting.
8. Summary
Feature | Code Example |
---|---|
Check if ON/OFF | if mySwitch.isOn { print("ON") } |
Set Color | mySwitch.onTintColor = .green |
Save Switch State | UserDefaults.standard.set(mySwitch.isOn, forKey: "state") |
Dark Mode Toggle | overrideUserInterfaceStyle = .dark |
Detect Switch Change | addTarget(self, action: #selector(switchChanged), for: .valueChanged) |
Conclusion
UISwitch
is a simple ON/OFF toggle for settings.- Supports custom colors, persistence with UserDefaults, and event handling.
- Common Uses: Dark mode, notifications, privacy settings.
Would you like a complete settings page example with UISwitch
? 🚀