본문 바로가기
카테고리 없음

How to setup UINavigation programmatically

by Eisen Sophie 2021. 6. 6.

(Left): a vc that appears when the app initiate (Right): next vc that appears when the button is clicked

In scene delegate class you have to set up like this

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        window?.rootViewController = UINavigationController(rootViewController: BaseViewController())
        window?.makeKeyAndVisible()
        
        guard let _ = (scene as? UIWindowScene) else { return }
    }

 

then you need main vc that begins when the app initiate

 

class BaseViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "chevron.right"), style: .plain, target: self, action: #selector(buttonHandler))
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.isTranslucent = true
        setupUI()
    }
    
    @objc func buttonHandler() {
        let vc = ViewController1()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func setupUI() {
        navigationController?.navigationBar.isTranslucent = true
        view.backgroundColor = .red
        navigationController?.navigationBar.barTintColor = .cyan
        navigationItem.title = "Main"
    }
}

 

when the user click the button on the right corner of the screen, following vc appears

class ViewController1: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupUI()
    }
    
    func setupUI(){
        view.backgroundColor = .orange
        navigationController?.navigationBar.isTranslucent = false
        navigationItem.title = "VC 1"
        navigationController?.navigationBar.barTintColor = .gray
    }
}