iosuinavigationcontrolleruinavigationbarprogrammatically-createdrightbarbuttonitem

Swift iOS -NavigationBar and RightBarButtonItem not Showing


I looked on SO for the answer to this and couldn't find it. Programmatic really isn't my thing but I intend on learning it around the beginning of July.

I'm using Storyboards. I have a NavVC that has a RedVC as root and the RedVC pushes on a BlueVC. They are all connected by segues. I have a PurpleVC that is in the Storyboard but it is not connected to anything

NavVC->RedVC->BlueVC //segues

              PurpleVC //no segue

In my BlueVC I have a collectionView and I when I press a cell I want to modally present the PurpleVC which I'm doing successfully using:

BlueVC:ViewController, CollectionViewControllerDele..., CollectionViewControllerData...{

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let purpleVC = storyboard?.instantiateViewController(withIdentifier: "PurpleVC") as! PurpleVC
        purpleVC.data = data[indexPath.row]

        purpleVC.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissVC))

        navigationController?.present(purpleVC, animated: true, completion: nil)
    }

@objc fileprivate func dismissVC(){
    dismiss(animated: true, completion: nil)
   }
}

The problem is I don't get a navigationBar nor the rightBarButtonItem when the purpleVC is presented modally. I tried adding it to the PurpleVC's navigationItem in the collectionView's didSelectItemAt but nothing showed up so then I tried adding it in the PurpleVC's viewDidLoad but nothing showed up there either.

PurpleVC:

PurpleVC:UIViewController{

var data:SomeClass?

override func viewDidLoad() {
        super.viewDidLoad()

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

@objc fileprivate func dismissVC(){
    dismiss(animated: true, completion: nil)
   }
}

How come my navigationBar and rightBarButtonItem aren't showing when the PurpleVC is presented modally?


Solution

  • When you are presenting a controller it wont come with navigation bar & items. Go to your purpleVC storyboard file and manually add the Navigation bar and items. Hope it will help!.