Change Image of UIBarButtonItem

I tried to change default button of Navigation Controller's backbutton with a new image.

I used the following code, but never changed.


UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithImage:[UIImage imageNamed:@"backbutton.png"]
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
   
    self.navigationItem.backBarButtonItem = backButton;


My iOS is iOS 8.4 and XCode is 7.1.

Why image is not changed?

I

Answered by Batuman in 81120022

I used this code for the backbutton and it works.


UIButton *imageButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [imageButton setBackgroundImage:[UIImage imageNamed:@"backbutton.png"] forState:UIControlStateNormal];
    [imageButton addTarget:self action:@selector(messageButtonTapped) forControlEvents:UIControlEventAllEvents];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imageButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
Accepted Answer

I used this code for the backbutton and it works.


UIButton *imageButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [imageButton setBackgroundImage:[UIImage imageNamed:@"backbutton.png"] forState:UIControlStateNormal];
    [imageButton addTarget:self action:@selector(messageButtonTapped) forControlEvents:UIControlEventAllEvents];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imageButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
Change Image of UIBarButtonItem
 
 
Q