Setting a Custom Image for a Back Button on UINavigationBar
iphone, objective-c, uibutton, uinavigationcontroller, xcode
Solution
try this code
UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *backBtnImage = [UIImage imageNamed:@"BackBtn.png"] ;
[backBtn setBackgroundImage:backBtnImage forState:UIControlStateNormal];
[backBtn addTarget:self action:@selector(goback) forControlEvents:UIControlEventTouchUpInside];
backBtn.frame = CGRectMake(0, 0, 54, 30);
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn] ;
self.navigationItem.leftBarButtonItem = backButton;
then define goback method like this
- (void)goback
{
[self.navigationController popViewControllerAnimated:YES];
}
Problem
I am trying to set a custom image for the back button that automatically gets place onto a navigation bar when a new view is pushed onto the stack. I have tried adding the following in the viewDidLoad of the parent viewController: ``` [[UIBarButtonItem appearance] setBackButtonBackgroundImage:[UIImage imageNamed:@"BackButton.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; ``` I have also tried the following: ``` UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"BackButton.png"] style:UIBarButtonItemStyleBordered target:nil action:nil]; self.navigationItem.backBarButtonItem = btn; ``` Using UIAppearance produces quite strange results: