How do I use UIKit programmatically without storyboards in Swift?

Using UIKit programmatically in Swift allows developers to create user interfaces without the need for storyboards. This approach provides greater flexibility and control over the UI components, making it easier to manage complex layouts and dynamic content. Below is a simple example of how to use UIKit programmatically to create a basic application with a label and a button.

import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Set the background color of the view view.backgroundColor = .white // Create a label let label = UILabel() label.text = "Hello, UIKit!" label.textAlignment = .center label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) // Create a button let button = UIButton(type: .system) button.setTitle("Press Me", for: .normal) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) view.addSubview(button) // Set up constraints NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: view.centerXAnchor), label.centerYAnchor.constraint(equalTo: view.centerYAnchor), button.centerXAnchor.constraint(equalTo: view.centerXAnchor), button.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 20) ]) } @objc func buttonTapped() { print("Button was tapped!") } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWith options: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = ViewController() window?.makeKeyAndVisible() return true } }

UIKit Swift programmatic UI iOS development no storyboards