Adding UIBarButton item in swift

2019-02-06 03:36发布

问题:

I'm trying to add a UIBarButton item to my nav bar.

Here is my Navigation Bar class declaration:

import UIKit

class NavigationBarController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        configureToolbar()        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // #pragma mark - Navigation bar data source

    func configureToolbar() {
        let toolbarButtonItems = [
            searchBarButtonItem
        ]
        toolbar.setItems(toolbarButtonItems, animated: true)
    }

    var searchBarButtonItem: UIBarButtonItem {
        return UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "barButtonItemClicked:")
    }
}

No error in compiler, but all I get is a plain navigation bar.

How do I get the UIBarButtonItem to show up?

回答1:

To add items to the NavigationBar of a NavigationController, or a NavigationBar added to a ViewController, you will need to first go through NavigationItem. Try this:

self.navigationItem.setRightBarButtonItems(navigationBarButtonItemsArray, animated: true)

// Or if you just want to insert one item.

self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "barButtonItemClicked:"), animated: true)

To switch the button to the left side, just replace setRightBarButtonItem to setLeftBarButtonItem or setLeftBarButtonItems.



回答2:

You can add multiple buttons to right side or left side of the navigation bar. I wil show u to add on right side and you can do the same for left side too

override func viewDidLoad()
{
    let Nam1BarBtnVar = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: #selector(Nam1BarBtnKlkFnc(_:)))
    let Nam2BarBtnVar = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(Nam2BarBtnKlkFnc(_:)))

    self.navigationItem.setRightBarButtonItems([Nam1BarBtnVar, Nam2BarBtnVar], animated: true)
}

func Nam1BarBtnKlkFnc(BtnPsgVar: UIBarButtonItem)
{
    print("Nam1BarBtnKlk")
}

func Nam2BarBtnKlkFnc(BtnPsgVar: UIBarButtonItem)
{
    print("Nam2BarBtnKlk")
}


回答3:

Updated for Swift 3:

Use the code below to add a UIBarButton item programmatically.

To add left bar button:

  self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "your_image_name"), style:  UIBarButtonItemStyle.plain, target: self, action: #selector(yourViewControllerName.barButtonClickAction))

To add right bar button:

  self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "your_image_name"), style:  UIBarButtonItemStyle.plain, target: self, action: #selector(yourViewControllerName.barButtonClickAction))

Method definition:

func barButtonClickAction() {
    print("Button click...")
}