简体   繁体   中英

iOS - Change only backBarButtonItem text color on a navigation bar

I'm trying to change the color of the backBarButtonItem on a navigation bar in my app (iOS 9+).

I can do this with :

 [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];

But this will change the color for all UIBarButtonItems on the navigation bar and I only want to change the back button.

I have tried :

[self.navigationItem.leftBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];

and

[self.navigationItem.leftBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];

But it doesn't work

NOTE: I want to keep the < arrow of the system back button so using a custom view is not an option unless I use a custom image

In the end I used the following solution:

1. Set the general appearance of UIBarbuttonitem BEFORE adding the right bar button item

[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor]} forState:UIControlStateNormal];

2. Then set the right bar button item and its specific appearance

UIBarButtonItem *rigthBtn = [[UIBarButtonItem alloc] initWithTitle:@"title" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnTapped:)];

[rigthBtn setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} forState:UIControlStateNormal];

[self.navigationItem setRightBarButtonItem:rigthBtn];

As per my comment posting sample code

    UIButton *useButton = [UIButton buttonWithType:UIButtonTypeCustom];
    useButton.frame = CGRectMake(0, 0, 20,17);
    useButton.layer.masksToBounds = NO;
    useButton.layer.shadowOffset = CGSizeMake(3, 3);
    useButton.layer.shadowRadius = 3;
    useButton.layer.shadowOpacity = 0.1;
    useButton.layer.shadowColor = [UIColor blackColor].CGColor;
    useButton.backgroundColor = [UIColor clearColor];
    useButton.tintColor = [UIColor whiteColor];
    [useButton setImage:[UIImage imageNamed:@"image if any"] forState:0];
    [useButton addTarget:self action:@selector(btnBackTapped:) forControlEvents:UIControlEventTouchUpInside];

    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:useButton]];

`

One year too late but did you tried to set the tintColor? I dont know your syntax but in swift it would be:

navigationController.navigationBar.tintColor = UIColor.COLOR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM