Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jazzedge/30349a4b1c7bec39192fc3ffe5535bfc to your computer and use it in GitHub Desktop.
Save jazzedge/30349a4b1c7bec39192fc3ffe5535bfc to your computer and use it in GitHub Desktop.
See: https://www.hackingwithswift.com/example-code/uikit/how-to-add-a-bar-button-to-a-navigation-bar
If you build a stack of view controllers with a navigation controller, but without embedding a VC in the NC then you have to add the navigation bar and buttons programmatically to every VC.
01. Example with a title, left and right button
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.title = "Profile Settings"
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
}
@objc func addTapped() {
//Do something if the bar buttons are tapped
}
02. Example with a title and two buttons on the right:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Third VC"
let add = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
let play = UIBarButtonItem(title: "Play", style: .plain, target: self, action: #selector(addTapped))
self.navigationItem.rightBarButtonItems = [add, play]
}
@objc func addTapped() {
//Do something if the bar buttons are tapped
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment