Add button to navigationbar programmatically

Objective CIphoneUinavigationbarUibarbuttonitem

Objective C Problem Overview


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, programatically by;

navBar=[[UINavigationBar alloc]initWithFrame:CGRectMake(0,0,320,44) ];

Similarly, I need to add the button, on the right side of this navigation bar. For that I used,

1.  

    UIView* container = [[UIView alloc] init];

    // create a button and add it to the container
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 130, 44.01)];
    [container addSubview:button];
    [button release];

    // add another button
    button = [[UIButton alloc] initWithFrame:CGRectMake(160, 0, 50, 44.01)];
    [container addSubview:button];
    [button release];

    // now create a Bar button item
    UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:container];

    // set the nav bar's right button item
    self.navigationItem.rightBarButtonItem = item;
    [item release];

2.  

    UIImage *im;
    im=[UIImage imageNamed:@"back.png"];
    [button setImage:im forState:UIControlStateNormal];
    [im release];
    backButton = [[UIBarButtonItem alloc] initWithCustomView:button];		
    [backButton setImageInsets:UIEdgeInsetsMake(0, -10,5, 5)];
    [self.navigationItem setRightBarButtonItem:backButton];

3.  

    UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc] initWithTitle:@"button"               style:UIBarButtonItemStylePlain target:self action:@selector(refreshLogsAction:)];
    self.navigationItem.rightBarButtonItem = refreshItem;

    [refreshItem release];

I tried all these ways, but none is displaying the button on the right hand side.

Objective C Solutions


Solution 1 - Objective C

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 - Objective C

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 - Objective C

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 - Objective C

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 - Objective C

self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction:)]autorelease];

-(void)saveAction:(UIBarButtonItem *)sender{

//perform your action

}

Solution 6 - Objective C

Swift version, add this in viewDidLoad:

var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneButton:")
navigationItem.rightBarButtonItem = doneButton

And this in your View Controller class

func doneButton(sender: UIBarButtonItem) {
    println(111)
}

Solution 7 - Objective C

Use following code:

UIBarButtonItem *customBtn=[[UIBarButtonItem alloc] initWithTitle:@"Custom" style:UIBarButtonItemStylePlain target:self action:@selector(customBtnPressed)];
[self.navigationItem setRightBarButtonItem:customBtn];

Solution 8 - Objective C

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...!!!

Solution 9 - Objective C

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

Solution 10 - Objective C

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.
  }

Solution 11 - Objective C

If you are not looking for a BarButtonItem but simple button on navigationBar then below code works:

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setBackgroundImage:[UIImage imageNamed:@"NavBar.png"] forState:UIControlStateNormal];
[aButton addTarget:self
            action:@selector(showButtonView:)
  forControlEvents:UIControlEventTouchUpInside];
aButton.frame = CGRectMake(260.0, 10.0, 30.0, 30.0);
[self.navigationController.navigationBar addSubview:aButton];

Solution 12 - Objective C

Hello everyone !! I created the solution to the issue at hand where Two UIInterface orientations are wanted using the UIIMagePicker.. In my ViewController where I handle the segue to the UIImagePickerController

**I use a..

-(void) editButtonPressed:(id)sender {
   BOOL editPressed = YES;
    NSUserDefaults *boolDefaults = [NSUserDefaults standardUserDefaults];
    [boolDefaults setBool:editPressed forKey:@"boolKey"];
    [boolDefaults synchronize];
    
    [self performSegueWithIdentifier:@"photoSegue" sender:nil]; 
    
}

**

Then in the AppDelegate Class I do the following.

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    
    BOOL appDelBool;
    NSUserDefaults *boolDefaults = [NSUserDefaults standardUserDefaults];
    appDelBool = [boolDefaults boolForKey:@"boolKey"];
    
       if (appDelBool == YES)
           return (UIInterfaceOrientationMaskPortrait);
        else
            return UIInterfaceOrientationMaskLandscapeLeft;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmacView Question on Stackoverflow
Solution 1 - Objective CXetiusView Answer on Stackoverflow
Solution 2 - Objective CBhavesh NayiView Answer on Stackoverflow
Solution 3 - Objective CJabbarView Answer on Stackoverflow
Solution 4 - Objective CrafView Answer on Stackoverflow
Solution 5 - Objective CGurpreet SinghView Answer on Stackoverflow
Solution 6 - Objective CEsqarrouthView Answer on Stackoverflow
Solution 7 - Objective CHimanshu MahajanView Answer on Stackoverflow
Solution 8 - Objective CSalman IftikharView Answer on Stackoverflow
Solution 9 - Objective CiAnkitView Answer on Stackoverflow
Solution 10 - Objective CJaywant KhedkarView Answer on Stackoverflow
Solution 11 - Objective CikingView Answer on Stackoverflow
Solution 12 - Objective CJohn ZView Answer on Stackoverflow