Home > Software engineering >  Navigation Bar, not displaying on second ViewController
Navigation Bar, not displaying on second ViewController

Time:11-03

I have created a navigation controller. I added a plus button to the top right of the navigation controller which opens up a new view controller. However, I want the navigation bar to show up on the new screen as well. But it's not showing. What am I doing wrong, or what am I missing? Here is my code:

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var toDoListTextView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Setting the Title for the nav bar
        title = "To Do List"
        configureNavigationItems()
    }
    
    private func configureNavigationItems(){
        
        /* Adding a button on the top right of the screen
         * in the navigation bar/controller.
         */
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(
            barButtonSystemItem: .add,
            target: self,
            action: #selector(didTapPlus)
        )
        
    }
    
    @objc func didTapPlus(){
        let vc = storyboard?.instantiateViewController(identifier: "makeTask") as! makeTaskViewController
        vc.modalPresentationStyle = .fullScreen
        
        vc.title = "Create a Task"
        vc.view.backgroundColor = .black
        
        vc.navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "Back",
            style: .done,
            target: self,
            action: nil)
        
        present(vc, animated: true)
    }
}

Storyboard

Newly-presented view controller gets a navigation bar

CodePudding user response:

Try this!

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var toDoListTextView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
    
        //Setting the Title for the nav bar
        title = "To Do List"
        configureNavigationItems()
    }

    private func configureNavigationItems(){

        navigationItem.rightBarButtonItem = UIBarButtonItem(
            barButtonSystemItem: .add,
            target: self,
            action: #selector(didTapPlus)
        )
    
    }

@objc func didTapPlus(){
    
    let vc = storyboard?.instantiateViewController(identifier: "makeTask") as! makeTaskViewController
    vc.modalPresentationStyle = .fullScreen
    
    vc.title = "Create a Task"
    vc.view.backgroundColor = .black
    
    vc.navigationItem.leftBarButtonItem = UIBarButtonItem(
        title: "Back",
        style: .done,
        target: self,
        action: nil)
    
    navigationController?.pushViewController(vc, animated: true)
    //present(vc, animated: true)
    }
}

  • Related