Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to change text and text color of navigationitem's back button

I am trying to set the backbutton text color (to red) of my navbar using the code below. (NOTE: The code below is already in the 'previous' view controller, in this case in the 'Popular' view controller:

//Customize Back button
UIView *backButtonView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 40)];
UILabel *backButtonLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 30, 40)];
backButtonLabel.text = @"back";
backButtonLabel.textColor = [UIColor colorWithHexString:@"cf212a"];
[backButtonView addSubview:backButtonLabel];

UIBarButtonItem *backButton = [[UIBarButtonItem alloc]initWithCustomView:backButtonView];
self.navigationItem.backBarButtonItem = backButton;

However, I am not getting the effect I want. I am still getting the default white color text in the backbutton. The text is not changed to 'back' as well

enter image description here

How can I resolve this?

like image 351
Zhen Avatar asked Feb 24 '23 12:02

Zhen


2 Answers

I believe that only the title property matters in the back button item; it is there to let you have a long title in the middle and a shorter title in the back button.

The easiest way to add a custom "back button" is to set UINavigationItem.leftBarButtonItem; you'll have to set its target/action appropriately.

like image 36
tc. Avatar answered Apr 09 '23 00:04

tc.


Thats because the backbuttonitem is a uibarbuttonitem that will be seen on the next view controller which will be pushed on top of your current view controller and not of the current view controller.

If you want to set the backbutton of the current view like you are trying to do in your above code than just move the code to the view controller that is shown before it(below it in the stack.) so that when you push the view controller for which you want to show custom back button which was set in the previous view controller. This is because the back button belongs to the previous view controller that is gonna push your new view controller...

like image 74
Robin Avatar answered Apr 09 '23 00:04

Robin