Question

I want to remove background of a UIViewController backbutton.

How can I do that?

I tried following code

backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back.png"] landscapeImagePhone:nil style:UIBarButtonSystemItemCancel target:self action:nil];
    [backButton setBackgroundImage:nil forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
self.navigationItem.backBarButtonItem = backButton;

But it didn't work!

Was it helpful?

Solution 3

This code worked for me

UIImage *backButtonImage = [UIImage imageNamed:@"back.png"];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
[backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];
[backButton setFrame:CGRectMake(0, 0, 30, 30)];
UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
[backBarButton setAction:@selector(backButtonPressed)];
self.navigationItem.leftBarButtonItem = backBarButton;
-(void)backButtonPressed{
    [self.navigationController popViewControllerAnimated:YES];
}

OTHER TIPS

Dont try to modify UINavigationBar's backbutton image. That's not possible because that comes by default.

Rather put another customize UIButton as UINavigationBar item and then you can customize that as per your needs.

UIButton *btnItem = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
[btnItem setTitle:@"title" forState:UIControlStateNormal];
[btnItem addTarget:self action:@selector(btnItem_click:) forControlEvents:UIControlEventTouchUpInside];
self.topItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btnItem];

UINavigation.backBarButtonItem is not used to set the back button of current view controller, it is used to set back button of controller pushed from current view controller.

Say now ViewController1 is showing in UINavigationController, you set backBarButton of ViewController1. The back button won't change, but then you push ViewController2, you'll see the back button of ViewController2 is what you set for ViewController1.

To set back button of ViewController1, either you set it in the ViewController pushing ViewController1, or you user self.navigationItem.leftBarbuttonItem = YourButton, the latter way you need to add event listener on YourButton

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top