Add button to navigationbar programmatically
Solution 1:
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.
Solution 2:
UIImage* image3 = [UIImage imageNamed:@"back_button.png"];
CGRect frameimg = CGRectMake(15,5, 25,25);
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(Back_btn:)
forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];
UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem =mailbutton;
[someButton release];
///// called event
-(IBAction)Back_btn:(id)sender
{
//Your code here
}
SWIFT:
var image3 = UIImage(named: "back_button.png")
var frameimg = CGRect(x: 15, y: 5, width: 25, height: 25)
var someButton = UIButton(frame: frameimg)
someButton.setBackgroundImage(image3, for: .normal)
someButton.addTarget(self, action: Selector("Back_btn:"), for: .touchUpInside)
someButton.showsTouchWhenHighlighted = true
var mailbutton = UIBarButtonItem(customView: someButton)
navigationItem?.leftBarButtonItem = mailbutton
func back_btn(_ sender: Any) {
//Your code here
}
Solution 3:
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.
}
Solution 4:
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) {
}
Solution 5:
self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction:)]autorelease];
-(void)saveAction:(UIBarButtonItem *)sender{
//perform your action
}