iOS Swift 4 Coding

How to add navigation bar buttons to an iOS app using Xcode and Swift 4?

11 views August 24, 2018 August 24, 2018 bicobro 0

When you want to add navigation buttons to the right top of a view in your iOS app you need to perform the steps below. If you need to add navigation bar buttons that must be visible when a specific tab of a tab controller navigation bar is selected, read more about it here.

  1. When you created an app using the storyboard, first attach a view-controller-class to the view.
  2. Create navigation bar icons. The size must be between 24×24 to 28×28 with the sizes @2x and @3x.
  3. Add the icons to Assets.xcassets. In the example below I added “buttonA_icon” and “buttonB_icon”.
  4. After that add the following code to the view-controller-class.
override func viewDidLoad() {
    super.viewDidLoad().        // Don't forget this row!
    initNavigationBarButtons()
}

private func initNavigationBarButtons() {
    let navBarButtonA = createNavBarButtonA()
    let navBarButtonB = createNavBarButtonB()
    navigationItem.rightBarButtonItems = [navBarButtonA, navBarButtonB]
}

private func createNavBarButtonA() -> UIBarButtonItem {
    let image = UIImage(named: "default_tab_bar_icon") // Size between 24x24 and 28x28 (@2x + @3x)
    return UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(TabIssuePortfolioViewController.didTapButtonA))
}
    
private func createNavBarButtonB() -> UIBarButtonItem {
    let image = UIImage(named: "default_tab_bar_icon")
    return UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(TabIssuePortfolioViewController.didTapButtonB))
}

...

@objc func didTapButtonA(sender: UIBarButtonItem) {
    
}

@objc func didTapButtonB(sender: UIBarButtonItem) {
    
}

 

Was this helpful?