import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let button = UIButton(type: .system)
button.setTitle("Go to Details", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(goToDetails), for: .touchUpInside)
view.addSubview(button)
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
@objc func goToDetails() {
let detailVC = DetailViewController()
navigationController?.pushViewController(detailVC, animated: true)
}
}
class DetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let label = UILabel()
label.text = "Detail Screen"
label.font = UIFont.systemFont(ofSize: 24, weight: .medium)
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
}
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let navController = UINavigationController(rootViewController: HomeViewController())
window?.rootViewController = navController
window?.makeKeyAndVisible()
return true
}
}We create a UIButton in HomeViewController and center it using Auto Layout. The button's title is set to 'Go to Details'. We add a target action goToDetails that is called when the button is tapped.
In goToDetails, we create an instance of DetailViewController and push it onto the navigation stack using navigationController?.pushViewController. This performs the programmatic navigation.
The DetailViewController shows a centered UILabel with the text 'Detail Screen'.
The app uses a UINavigationController as the root controller to enable navigation.