Bird
Raised Fist0
iOS Swiftmobile~20 mins

Toggle switch in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Toggle Switch Screen
This screen shows a toggle switch that the user can turn on or off. When the switch is on, a label below it says "Switch is ON". When off, the label says "Switch is OFF".
Target UI
-----------------------
| Toggle Switch Screen |
-----------------------
|                     |
|    [  UISwitch  ]   |
|                     |
|   Switch is OFF     |
|                     |
-----------------------
Add a UISwitch centered horizontally near the top.
Add a UILabel below the switch to show the switch state text.
When the switch is toggled, update the label text to "Switch is ON" or "Switch is OFF" accordingly.
Use Auto Layout to center the switch and label vertically spaced.
The label text should update immediately when the switch changes.
Starter Code
iOS Swift
import UIKit

class ToggleSwitchViewController: UIViewController {

    let toggleSwitch = UISwitch()
    let stateLabel = UILabel()

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

        // TODO: Add toggleSwitch to view and set constraints

        // TODO: Add stateLabel to view and set constraints

        // TODO: Set initial label text

        // TODO: Add target action for toggleSwitch value change
    }

    // TODO: Implement method to update label text when switch changes
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
import UIKit

class ToggleSwitchViewController: UIViewController {

    let toggleSwitch = UISwitch()
    let stateLabel = UILabel()

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

        toggleSwitch.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(toggleSwitch)
        NSLayoutConstraint.activate([
            toggleSwitch.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            toggleSwitch.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40)
        ])

        stateLabel.translatesAutoresizingMaskIntoConstraints = false
        stateLabel.textAlignment = .center
        stateLabel.font = UIFont.systemFont(ofSize: 18)
        stateLabel.text = "Switch is OFF"
        view.addSubview(stateLabel)
        NSLayoutConstraint.activate([
            stateLabel.topAnchor.constraint(equalTo: toggleSwitch.bottomAnchor, constant: 20),
            stateLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])

        toggleSwitch.addTarget(self, action: #selector(switchToggled), for: .valueChanged)
    }

    @objc func switchToggled() {
        if toggleSwitch.isOn {
            stateLabel.text = "Switch is ON"
        } else {
            stateLabel.text = "Switch is OFF"
        }
    }
}

We add a UISwitch and UILabel to the view and use Auto Layout to center them horizontally. The switch is placed near the top with some padding from the safe area. The label is placed below the switch with vertical spacing.

We set the label's initial text to "Switch is OFF". Then we add a target action to the switch for the .valueChanged event. When the switch toggles, the switchToggled method updates the label text to show the current state.

This approach keeps the UI simple and responsive, and the label updates immediately when the user toggles the switch.

Final Result
Completed Screen
-----------------------
| Toggle Switch Screen |
-----------------------
|                     |
|    [  UISwitch  ]   |
|                     |
|    Switch is ON     |
|                     |
-----------------------
User taps the switch to toggle it on or off.
Label text below the switch updates instantly to "Switch is ON" or "Switch is OFF".
Stretch Goal
Add a second label below the state label that shows the current time when the switch was last toggled.
💡 Hint
Use DateFormatter to format the current time and update the label inside the switchToggled method.

Practice

(1/5)
1. What does a UISwitch control in an iOS app?
easy
A. It lets users toggle between on and off states.
B. It displays a list of options to select from.
C. It shows a progress bar for tasks.
D. It opens a new screen when tapped.

Solution

  1. Step 1: Understand the purpose of UISwitch

    A UISwitch is designed to let users turn a setting on or off with a simple tap.
  2. Step 2: Compare with other UI controls

    Unlike lists or progress bars, UISwitch specifically toggles between two states: on and off.
  3. Final Answer:

    It lets users toggle between on and off states. -> Option A
  4. Quick Check:

    UISwitch = toggle on/off [OK]
Hint: UISwitch always toggles between two states [OK]
Common Mistakes:
  • Confusing UISwitch with buttons that open new screens
  • Thinking UISwitch shows progress or lists
  • Assuming UISwitch can select multiple options
2. Which of the following is the correct way to create a UISwitch in Swift?
easy
A. let toggle = UISwitch.new()
B. let toggle = Switch()
C. let toggle = UISwitch()
D. let toggle = UISwitch.create()

Solution

  1. Step 1: Recall UISwitch initialization syntax

    In Swift, UI elements like UISwitch are created by calling their initializer with parentheses.
  2. Step 2: Check each option

    Only UISwitch() is the correct initializer. The others use invalid methods or class names.
  3. Final Answer:

    let toggle = UISwitch() -> Option C
  4. Quick Check:

    Initialize UISwitch with UISwitch() [OK]
Hint: Use parentheses to create UISwitch instance [OK]
Common Mistakes:
  • Using incorrect class name like Switch
  • Trying to call .new() or .create() methods
  • Omitting parentheses when creating UISwitch
3. What will be printed when this Swift code runs?
let toggle = UISwitch()
toggle.isOn = true
print(toggle.isOn)
medium
A. Compilation error
B. false
C. nil
D. true

Solution

  1. Step 1: Understand the isOn property

    The isOn property of UISwitch indicates if the switch is on (true) or off (false).
  2. Step 2: Analyze the code

    The code sets toggle.isOn = true and then prints toggle.isOn, so it will print true.
  3. Final Answer:

    true -> Option D
  4. Quick Check:

    Setting isOn true prints true [OK]
Hint: Print isOn after setting it to see true/false [OK]
Common Mistakes:
  • Assuming default is false without setting
  • Confusing isOn with other properties
  • Expecting nil or error from print
4. Identify the error in this Swift code that tries to detect switch changes:
let toggle = UISwitch()
toggle.addTarget(self, action: #selector(switchChanged), for: .valueChanged)

@objc func switchChanged() {
    print("Switch toggled")
}
medium
A. Wrong event type used in addTarget
B. Missing parameter in switchChanged method
C. UISwitch cannot use addTarget
D. Missing UISwitch initialization

Solution

  1. Step 1: Check addTarget usage

    The addTarget method requires the action method to accept the sender parameter.
  2. Step 2: Analyze switchChanged method signature

    The method switchChanged() has no parameters but should accept _ sender: UISwitch.
  3. Final Answer:

    Missing parameter in switchChanged method -> Option B
  4. Quick Check:

    Action method needs sender parameter [OK]
Hint: Action methods need sender parameter for addTarget [OK]
Common Mistakes:
  • Omitting sender parameter in action method
  • Using wrong event type like .touchUpInside
  • Thinking UISwitch can't use addTarget
5. You want to create a toggle switch that updates a label text to "ON" or "OFF" when toggled. Which code snippet correctly implements this behavior?
let toggle = UISwitch()
let label = UILabel()

// Which switchChanged method is correct?
hard
A. @objc func switchChanged(_ sender: UISwitch) { label.text = sender.isOn ? "ON" : "OFF" }
B. @objc func switchChanged() { label.text = toggle.isOn ? "ON" : "OFF" }
C. @objc func switchChanged(_ sender: UISwitch) { if sender.isOn == false { label.text = "ON" } else { label.text = "OFF" } }
D. @objc func switchChanged(_ sender: UISwitch) { label.text = "ON" }

Solution

  1. Step 1: Check method signature and parameter

    The action method must accept the sender UISwitch to get its current state.
  2. 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.
  3. 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.
  4. Final Answer:

    @objc func switchChanged(_ sender: UISwitch) { label.text = sender.isOn ? "ON" : "OFF" } -> Option A
  5. Quick Check:

    Use sender.isOn with ternary to update label [OK]
Hint: Use sender.isOn ? "ON" : "OFF" to update label [OK]
Common Mistakes:
  • Forgetting sender parameter in action method
  • Reversing ON and OFF text logic
  • Ignoring switch state and setting fixed text
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard