Wednesday, 26 February 2014

iPhone Development:Add multiple buttons to your navigation bar

Got a scenario in your app where you are required to show two or three buttons on your navigation bar. Left out the worries as in this tutorial or blog post, I am going to tell you how simple it is to place more buttons on navigation bar in place single default one. Let's jump on to this
In this post I am going to show you how we can add one more button to right of back button of navigation bar.
First, we have to create a container view that will hold all our buttons and give it a frame
UIView* container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 100)];

Now create a simple button and add it to container view as subview , here we will override default back button and place our own button with same image as default back button in IOS
        UIImage *image = [UIImage imageNamed:@"BackNew.png"];
        UIButton* backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 35,70,33)];
        [backButton  setBackgroundImage:image forState:UIControlStateNormal];
        [backButton setTitle:@"Back" forState:UIControlStateNormal];
        backButton.titleLabel.font=[UIFont boldSystemFontOfSize:12.0];
        [backButton addTarget:self action:@selector(navigateBack:) forControlEvents:UIControlEventTouchUpInside];
        [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [container addSubview:backButton];

We will create one more button in a same way as created above
        UIButton* buttonSelectAllWorksheets = [UIButton buttonWithType:UIButtonTypeCustom];
        buttonSelectAllWorksheets.frame=CGRectMake(85, 35, 82, 32);
        [buttonSelectAllWorksheets setTitle:@"Slct wrksts" forState:UIControlStateNormal];
        buttonSelectAllWorksheets.titleLabel.font=[UIFont boldSystemFontOfSize:12.0];
        [buttonSelectAllWorksheets setBackgroundImage:[UIImage imageNamed:@"ButtonNormalNew.png"] forState:UIControlStateNormal];
        [buttonSelectAllWorksheets setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [buttonSelectAllWorksheets addTarget:self action:@selector(selectAlWorkSheets:) forControlEvents:UIControlEventTouchUpInside];
        [container addSubview:buttonSelectAllWorksheets];

Now we have two buttons that were added to our container view.At this time we will create a barButtonItem and initialize it with custom view i.e our container view
      UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:container];

Now, we had barButtonItem and we can give it to our navigationItem as leftBarButtonItem.
 self.navigationItem.leftBarButtonItem = item;
Release container view and item. 3UUSYYCF48RC
     [container release];
     [item release];

The above code will generate an output as shown in given below image

No comments:
Write comments