1

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

compbealov
  • 37
  • 8

3 Answers3

6

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.

Miknash
  • 7,888
  • 3
  • 34
  • 46
  • thanks lot ) i have created left and right button. but how can i change them to other buttons after action? – compbealov Jun 08 '15 at 10:22
  • you can change the item the same way you added it to the navigation in the view did load - that said you can use self.navigationItem.setLeftBarButtonItem( (UIBarButtonItem(title:"backButton", style: .Plain, target:self, action:"back_pressed:")), animated: false) with different parameters. – Miknash Jun 08 '15 at 10:26
1

Objective-C version

    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"close"] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = closeButton;

    //OR

    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = closeButton;
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
0

try this code-

self.title = "Title"

var left : UIBarButtonItem = UIBarButtonItem(title: "LeftButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: "")

var right : UIBarButtonItem = UIBarButtonItem(title: "RigthButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: "")

self.navigationItem.leftBarButtonItem = left
self.navigationItem.rightBarButtonItem = right
Ravi Gautam
  • 960
  • 2
  • 9
  • 20