Pages

Wednesday, August 24, 2011

[Code Snippet] Custom UINavigationBar back button

Back from my holidays, I come back with my weekly wednesday's code snippet.

Sometimes when we work with UINavigationcontroller we want to custom the back button for a more visual image, or just an arrow. Today let's see how to create a custom back button with our own image for the UINavigationBar.

First of all, you have to implement in viewDidLoad the next piece of code

    if ([self.navigationController.viewControllers count] > 1)
    {
        //Creating our custom back button
        UIButton *home = [UIButton buttonWithType:UIButtonTypeCustom];
        [home setTitle:@"Volver" forState:UIControlStateNormal];
       
        UIImage *homeImage = [UIImage imageNamed:@"backbutton.png"];
       
        [home setBackgroundImage:homeImage forState:UIControlStateNormal];
        home.frame = CGRectMake(0, 0, 80, 30);
       
        [home addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
       
        UIBarButtonItem *cancelButton = [[[UIBarButtonItem alloc]
                                          initWithCustomView:home] autorelease];
        self.navigationItem.leftBarButtonItem = cancelButton;
    }
After that, we just have to implement the selector to pop the view controller and back to the previous one:

-(IBAction)cancel:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
And that's all. Now you can improve your UI with a custom back button. Enjoy it

No comments:

Post a Comment