Reputation: 2746
Is it possible to change the back button on a UINavigationBar and change the title?
When I try to set the customView property, I get an image right next to the default button.
I use this code
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backButtonImage landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:nil action:nil];
I want the title to be "Back" which is easy enough to do in Storyboard. But the problem is that no matter if I use code above or use customView property, the default back button remains.
Upvotes: 1
Views: 2483
Reputation: 3663
You can add a UIImage
to the UIButton
. And, then use it as a custom back button. Here's a quick example:
// Custom image
UIImage *backButtonImage = [UIImage imageNamed:@"button-background-image.png"];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setFrame:CGRectMake(0, 0, 100, 30)];
[backButton setBackgroundImage:backButtonImage forState:UIControlStateNormal];
// Custom title
[backButton setTitle:@"Back" forState:UIControlStateNormal];
[backButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(barPayButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[backButton setShowsTouchWhenHighlighted:NO];
UIBarButtonItem *buttonOnBar =[[UIBarButtonItem alloc] initWithCustomView:backButton];
self.navigationItem.leftBarButtonItem = buttonOnBar;
Note: You will loose the chevron (system-provided back arrow) which was introduced in iOS7. It goes as a title and chevron together presenting your previous view controller.
Update:
You can also use UIEdgeInsets
to resize your image intelligently.
UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 0, 15, 10);
UIImage *backButtonImage = [[UIImage imageNamed:@"button-background-image.png"] resizableImageWithCapInsets:edgeInsets];
Upvotes: 2
Reputation: 11770
You can achieve what you want by setting the navigationItem.leftBarButtonItem
of the view controller that's being pushed to the custom bar button item with the look you want. Good Luck!
Upvotes: 0