Search code examples
iosswiftprogrammatically-created

How can I add UIBarButtonItem to my navigation controller programmatically?


I want to add UIBarButtonItem to my navigation controller programmatically in both left and right side and change both of them to other UIBarButtonItems when clicked. And also I want to use my item icons. Can i do that? Its my 2nd week in iOS programming excuse me if its a simple question


Solution

  • With image:

    self.navigationItem.setLeftBarButtonItem( (UIBarButtonItem(image:UIImage(named:"image"), style: .Plain, target:self, action:"action:")), animated: false)
    

    With title:

    self.navigationItem.setLeftBarButtonItem( (UIBarButtonItem(title:"backButton", style: .Plain, target:self, action:"back_pressed:")), animated: false)
    

    Furthermore, you can assign multiple items for each side:

    var test: UIBarButtonItem = UIBarButtonItem(image: UIImage(named:"test"), style: UIBarButtonItemStyle.Plain, target: self, action: "test1:")
    var test2: UIBarButtonItem = UIBarButtonItem(image: UIImage(named:"test2"), style: UIBarButtonItemStyle.Plain, target: self, action: "test2:")
    navigationItem.rightBarButtonItems = [test1, test2]
    

    When using multiple items you might be interested in:

    var spacing : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    

    which is used to have similar space between buttons.