1. Problem description
1.1. Operating environment
Xcode version: 7.3.1
Simulator version: 8.4 & 9.3
1.2. Background
In one project, the background color of the navigation bar is blue, and the return button of the navigation bar is white. Then the productization provides a cut image of the blue rgb value and the white return button.
Because directly setting the background color of the navigation bar has a semi-transparent effect, a solid color image is created and the background image of the navigation bar is set.
[self.navigationController.navigationBar setBackgroundImage:colorImage forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
The colorImage is a solid color image.
1.3. Problem
But after running it, it was found that the picture of the back button was clearly white, but it was indeed blue.
2. Solution
2.1. Ideas
First, by modifying the name of the picture, the possibility of the existence of a resource file with the same name is ruled out.
Then modified the background color of the navigation bar, and found that the color of the back button changes with the background color of the navigation bar.
Finally, look at the code to add the navigation button:
UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"GDNavBar_Back"] style:UIBarButtonItemStylePlain target:self action:@selector(didBackButton)];
The image loaded here uses a foreground image similar to the title. Analogous to the title, the title of the UIBarButtonItem has a transparent effect when displayed, so the foreground image may also have a transparent effect.
But UIBarButtonItem does not have a backgroundImage property, so it can only be displayed through customView.
UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 45, 40);
[btn setImage:[UIImage imageNamed:@"GDNavBar_Back"] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(backToPrev) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
After using this method, return to the picture to display normally.
2.2 Conclusion The
use of customView property UIBarButtonItem custom buttons.
3. Reason
As mentioned above, try to use customView to customize UIBarButtonItem.