A toggle switch lets users turn something on or off easily. It is like a light switch in your home.
Toggle switch in 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.
let toggleSwitch = UISwitch() toggleSwitch.isOn = false
toggleSwitch.addTarget(self, action: #selector(switchChanged), for: .valueChanged)@objc func switchChanged(_ sender: UISwitch) {
print("Switch state is \(sender.isOn ? "ON" : "OFF")")
}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.
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") } } }
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.
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.
Practice
UISwitch control in an iOS app?Solution
Step 1: Understand the purpose of UISwitch
A UISwitch is designed to let users turn a setting on or off with a simple tap.Step 2: Compare with other UI controls
Unlike lists or progress bars, UISwitch specifically toggles between two states: on and off.Final Answer:
It lets users toggle between on and off states. -> Option AQuick Check:
UISwitch = toggle on/off [OK]
- Confusing UISwitch with buttons that open new screens
- Thinking UISwitch shows progress or lists
- Assuming UISwitch can select multiple options
UISwitch in Swift?Solution
Step 1: Recall UISwitch initialization syntax
In Swift, UI elements like UISwitch are created by calling their initializer with parentheses.Step 2: Check each option
OnlyUISwitch()is the correct initializer. The others use invalid methods or class names.Final Answer:
let toggle = UISwitch() -> Option CQuick Check:
Initialize UISwitch with UISwitch() [OK]
- Using incorrect class name like Switch
- Trying to call .new() or .create() methods
- Omitting parentheses when creating UISwitch
let toggle = UISwitch() toggle.isOn = true print(toggle.isOn)
Solution
Step 1: Understand the isOn property
TheisOnproperty of UISwitch indicates if the switch is on (true) or off (false).Step 2: Analyze the code
The code setstoggle.isOn = trueand then printstoggle.isOn, so it will print true.Final Answer:
true -> Option DQuick Check:
Setting isOn true prints true [OK]
- Assuming default is false without setting
- Confusing isOn with other properties
- Expecting nil or error from print
let toggle = UISwitch()
toggle.addTarget(self, action: #selector(switchChanged), for: .valueChanged)
@objc func switchChanged() {
print("Switch toggled")
}Solution
Step 1: Check addTarget usage
TheaddTargetmethod requires the action method to accept the sender parameter.Step 2: Analyze switchChanged method signature
The methodswitchChanged()has no parameters but should accept_ sender: UISwitch.Final Answer:
Missing parameter in switchChanged method -> Option BQuick Check:
Action method needs sender parameter [OK]
- Omitting sender parameter in action method
- Using wrong event type like .touchUpInside
- Thinking UISwitch can't use addTarget
let toggle = UISwitch() let label = UILabel() // Which switchChanged method is correct?
Solution
Step 1: Check method signature and parameter
The action method must accept the sender UISwitch to get its current state.Step 2: Verify label text update logic
@objc func switchChanged(_ sender: UISwitch) { label.text = sender.isOn ? "ON" : "OFF" } uses a ternary operator to set label text to "ON" if switch is on, else "OFF", which is correct.Step 3: Review other options
@objc func switchChanged() { label.text = toggle.isOn ? "ON" : "OFF" } lacks sender parameter; @objc func switchChanged(_ sender: UISwitch) { if sender.isOn == false { label.text = "ON" } else { label.text = "OFF" } } reverses ON/OFF logic; @objc func switchChanged(_ sender: UISwitch) { label.text = "ON" } always sets "ON" ignoring switch state.Final Answer:
@objc func switchChanged(_ sender: UISwitch) { label.text = sender.isOn ? "ON" : "OFF" } -> Option AQuick Check:
Use sender.isOn with ternary to update label [OK]
- Forgetting sender parameter in action method
- Reversing ON and OFF text logic
- Ignoring switch state and setting fixed text
Ready to prove it?
Pass the test and this pattern moves unknown
