// set this as the Root viewController of a navigation controller class NavTestVC: UIViewController { var navID: Int = 0 @objc func btnTap(_ sender: Any?) { let vc = NavTestVC() vc.navID = self.navID + 1 navigationController?.pushViewController(vc, animated: true) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.95, alpha: 1.0) var config = UIButton.Configuration.filled() config.buttonSize = .medium config.cornerStyle = .medium config.title = "Push" let btnA = UIButton(configuration: config) btnA.addAction ( UIAction { _ in self.btnTap(nil) }, for: .touchUpInside ) let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) btnA.translatesAutoresizingMaskIntoConstraints = false view.addSubview(btnA) let g = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ label.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0), label.centerXAnchor.constraint(equalTo: g.centerXAnchor), btnA.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 40.0), btnA.centerXAnchor.constraint(equalTo: g.centerXAnchor), ]) label.text = "This navID: \(navID)" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("navID:", navID, #function) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("navID:", navID, #function) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("navID:", navID, #function) } }