1

I'm having a problem getting a button to show on a navigation controller. I have researched this and I think it has to do with how navigation works. Pushed and Popped from a stack.

Here is what I have:

I have the initial view as a navigation controller. This controller calls several views but the view that I'm having an issue with is a UICollectionViewController. This is called from a button click on the first viewController connected to the navigationController. I then have a segue setup that goes from the UICollectionViewCell to a new ViewController. So I'm assuming this is a second level NavigationController.

Secondly I have a Back Button Image that is displayed on my navigation instead of the text < Back.

The back button shows fine in the navigation controller on all the views except for the one called from the second level segue.

As I understand from reading other posts on this topic it is because a new navigation Controller is created on the second level segue.

I'm fine with that because everything works fine but I need the button to show on that second navcontroller.

I was trying to programmatically add the button to the navigation controller associated with the current view. I am using this code:

override func viewDidLoad() {
    super.viewDidLoad()
    var image = UIImage(named: "NavLogo")
    var back_image = UIImage(named: "BackButton")
    image = image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
    back_image = back_image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)


    self.navigationController?.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.plain, target: nil, action: nil)

    self.navigationController?.navigationItem.leftBarButtonItem = UIBarButtonItem(image: back_image, style: UIBarButtonItemStyle.plain, target: nil, action: nil)
 }

This code does not seem to add the button to the current navigation controller.

This project is using Swift 3 and Xcode 8

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

3

Use

self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.plain, target: nil, action: nil)

instead of

self.navigationController?.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.plain, target: nil, action: nil)

The reason for this is explained in this link.

Community
  • 1
  • 1
kerry
  • 2,362
  • 20
  • 33