user5590773
user5590773

Reputation:

Swift - How to set a different nav bar for each view?

enter image description hereI'm having trouble displaying different navigation bar button on different views.

I have a parent view navigation controller and 3 child views. What I would like to do is have different navigation bar buttons on each child view, and not just the same 2 which I could achieve through adding them on the main storyboard.

I have attached two screenshots so you can see what my storyboard and code looks like.

So basically I'm looking for some code to add bar items individually on each view. [![enter image description here][2]][2] enter image description here

Upvotes: 2

Views: 2447

Answers (1)

Peyman
Peyman

Reputation: 3077

In each view controller you can use self.navigationItem to make those changes individually.

For example, say you have a view controller names "VC1" and you want to have an add button in the navigation bar. In VC1, override viewDidLoad and do the following:

override func viewDidLoad() {
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addFunc")
}

UPDATE: So, looking at your tutorial I realized that you're not pushing the child view controllers to the navigation controller, you're just adding them as child. There is a difference. Every navigation controller has a set of view controllers (you can access this: navController.viewControllers)

You can add child view controllers but it would not be any different from other controllers, if you want to actually use a navigation controller, you need to push them to the navigation controller. Otherwise, you can't access navigationItem or similar features like that.

Instead of adding the view controllers to the scroll view, use this:

self.pushViewController(childViewController1, animated: true)

If you absolutely want to have it in the scroll view AND have different navigation bar buttons for every view controller, you'd have to implement this mechanism yourself. For example, check out this:

https://github.com/peymanmortazavi/UISwipeViewController

It's not polished, you'd have to implement the layout constraints properly but it demonstrates what I mean.

Upvotes: 5

Related Questions