Hi I need to set the button on right side, in navigation bar, programatically , so that if I press the button I will perform some actions. I have created the navigation bar
Simple use native editBarButton like this
self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self.navigationItem.rightBarButtonItem setAction:@selector(editBarBtnPressed)];
and then
- (void)editBarBtnPressed {
if ([infoTable isEditing]) {
[self.editButtonItem setTitle:@"Edit"];
[infoTable setEditing:NO animated:YES];
}
else {
[self.editButtonItem setTitle:@"Done"];
[infoTable setEditing:YES animated:YES];
}
}
Have fun...!!!
In ViewDidLoad method of ViewController.m
UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(back)];
[self.navigationItem setLeftBarButtonItem:cancel];
"(back)" selector is a method to dissmiss the current ViewController
How to add an add button to the navbar in swift:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "onAdd:")
onAdd:
func onAdd(sender: AnyObject) {
}
Try this.It work for me. Add button to navigation bar programmatically, Also we set image to navigation bar button,
Below is Code:-
UIBarButtonItem *Savebtn=[[UIBarButtonItem alloc]initWithImage:
[[UIImage imageNamed:@"bt_save.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain target:self action:@selector(SaveButtonClicked)];
self.navigationItem.rightBarButtonItem=Savebtn;
-(void)SaveButtonClicked
{
// Add save button code.
}
Inside my UIViewController
derived class, I am using the following inside viewDidLoad
:
UIBarButtonItem *flipButton = [[UIBarButtonItem alloc]
initWithTitle:@"Flip"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(flipView:)];
self.navigationItem.rightBarButtonItem = flipButton;
[flipButton release];
This adds a button to the right hand side with the title Flip, which calls the method:
-(IBAction)flipView
This looks very much like you #3, but it is working within my code.
To add search button on navigation bar use this code:
UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch:)];
self.navigationController.navigationBar.topItem.rightBarButtonItem = searchButton;
and implement following method:
- (IBAction)toggleSearch:(id)sender
{
// do something or handle Search Button Action.
}