some_id
some_id

Reputation: 29896

Add a button to a navigation toolbar

How can a button be added to a navigation toolbar in an application which is navigation based?

The rootController is a tableView by default, and this is perfect. I would like to add a "share" button to the navigation controller so that I can attach it to my own method.

How is this done if the navigation bar is added in the code somewhere?

Upvotes: 1

Views: 1341

Answers (4)

Convolution
Convolution

Reputation: 2351

To do it in code, go to your views viewDidLoad method and create a UIBarButtonItem

This code will create a button that says share like you wanted and put it on the right hand side of the navigation bar.

- (void)viewDidLoad {
     [super viewDidLoad];
     UIBarButtonItem *shareButton = [[UIBarButtonItem alloc] initWithTitle:@"Share"     style:UIBarButtonItemStyleBordered target:self action:@selector(share)];

    self.navigationItem.rightBarButtonItem = shareButton;
    [shareButton release];
}

Upvotes: 4

MHC
MHC

Reputation: 6405

You can create an UIBarButtonItem and attach it to a root view controller's navigation item. You add a target-action pair when you initialize the UIBarButtonItem object and that action message will be sent to the target on a user tapping on the button.

So if you want the button when the table view is shown, set the UIBarButtonItem to your table view controller's navigationItem.rightBarButtomItem property.

Upvotes: 0

DVG
DVG

Reputation: 17480

This makes an add button, but you get the idea.

self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
  target: 
  self action:@selector(buttonPressed:)] 
  autorelease];

Upvotes: 0

Zaky German
Zaky German

Reputation: 14334

UIBarButtonItem *shareButton = [[[UIBarButtonItem alloc] initWithTitle:@"Share" style:UIBarButtonItemStylePlain target:self action:@selector(yourShareAction)] autorelease];


self.navigationItem.rightBarButtonItem = shareButton;

Upvotes: 1

Related Questions