iOS Swift 4 Coding

How to add navigation bar buttons in a specific tab controller tab?

11 views August 25, 2018 August 26, 2018 bicobro 1

When you want to add navigation buttons to the right top of a tab that is part of a tab controller tab in your iOS app using Swift 4 and Xcode, perform the following steps.

  1. When you created an app using the storyboard, first attach a view-controller-class to the tab 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 of the specific tab.
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    showNavigationBarButtons()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    hideNavigationBarButtons()
}

private func showNavigationBarButtons() {
    let navBarButtonA = createNavBarButtonA()
    let navBarButtonB = createNavBarButtonB()
    self.tabBarController?.navigationItem.rightBarButtonItems = [navBarButtonA, navBarButtonB]
}

private func hideNavigationBarButtons() {
    self.tabBarController?.navigationItem.rightBarButtonItems = nil
}

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?