compbealov
compbealov

Reputation: 37

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

Upvotes: 1

Views: 1576

Answers (3)

Suhit Patil
Suhit Patil

Reputation: 12023

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;

Upvotes: 1

Miknash
Miknash

Reputation: 7948

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.

Upvotes: 6

Ravi Gautam
Ravi Gautam

Reputation: 978

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

Upvotes: 0

Related Questions