Changing the UINavigationBar background image with

2019-09-02 18:41发布

问题:

Right now, I have

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed: @"UINavigationBarBackground.png"] 
           forBarMetrics:UIBarMetricsDefault];

I want it to change the background on-click. Right now, it only changes after you restart the app. Is there a way to have it change the background image of the navigation bar without having to restart the app?

I tried

[[UINavigationBar appearance] setNeedsDisplay];

but it crashes with: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSMethodSignature getArgumentTypeAtIndex:]: index (2) out of bounds [0, 1]'

And if I try

[self.navigationController.navigationBar setNeedsDisplay];

or

[self.view setNeedsDisplay];

nothing happens.

回答1:

UINavigationBar is just another (but slightly special) subclassed UIView that Apple provides in iOS, so you should be able to force an update using something like "setNeedsDisplay" right after you adjust the image.