import UIKit
class SimpleButtonViewController: UIViewController {
let button = UIButton(type: .system)
let messageLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// Configure button
button.setTitle("Tap Me", for: .normal)
button.accessibilityLabel = "Tap Me Button"
button.translatesAutoresizingMaskIntoConstraints = false
// Configure label
messageLabel.text = ""
messageLabel.textAlignment = .center
messageLabel.accessibilityLabel = "Message Label"
messageLabel.translatesAutoresizingMaskIntoConstraints = false
// Add subviews
view.addSubview(button)
view.addSubview(messageLabel)
// Setup Auto Layout constraints
NSLayoutConstraint.activate([
button.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
messageLabel.topAnchor.constraint(equalTo: button.bottomAnchor, constant: 20),
messageLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
messageLabel.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 20),
messageLabel.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -20)
])
// Add button action handler
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
}
@objc func buttonTapped() {
messageLabel.text = "Button tapped!"
}
}We create a UIButton and UILabel as properties. In viewDidLoad, we set the button title to 'Tap Me' and add an accessibility label for screen readers. The label starts empty and is centered below the button. We use Auto Layout constraints to position the button near the top center and the label below it with some spacing. The button's touchUpInside event triggers the buttonTapped method, which updates the label text to 'Button tapped!'. This simple interaction shows how to handle button taps and update UI elements in Swift.