How do I handle navigation and modal presentations in Swift?

In Swift, managing navigation and modal presentations is achieved primarily through the use of view controllers. By utilizing UINavigationController for navigation and presenting view controllers modally, developers can create seamless and intuitive user experiences. Below are examples of how to handle navigation and modal presentations in a Swift-based application.

// Example of Navigation class MainViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let button = UIButton(type: .system) button.setTitle("Go to Detail", for: .normal) button.addTarget(self, action: #selector(navigateToDetail), for: .touchUpInside) view.addSubview(button) } @objc func navigateToDetail() { let detailVC = DetailViewController() navigationController?.pushViewController(detailVC, animated: true) } } // Example of Modal Presentation class DetailViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let button = UIButton(type: .system) button.setTitle("Present Modal", for: .normal) button.addTarget(self, action: #selector(presentModal), for: .touchUpInside) view.addSubview(button) } @objc func presentModal() { let modalVC = ModalViewController() modalVC.modalPresentationStyle = .fullScreen present(modalVC, animated: true, completion: nil) } } class ModalViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .blue let button = UIButton(type: .system) button.setTitle("Dismiss", for: .normal) button.addTarget(self, action: #selector(dismissSelf), for: .touchUpInside) view.addSubview(button) } @objc func dismissSelf() { dismiss(animated: true, completion: nil) } }

Swift Navigation Swift Modal Presentation iOS Development View Controller Management