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.