Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set UINavigationBar background image in ViewController

I am able to set the background for my navbar to a custom image in the app delegate didFinishLaunchingWithOptions method with this code:

UIImage *navBarImage;
navBarImage = [UIImage imageNamed:@"navbar.png"];

[[UINavigationBar appearance] setBackgroundImage: navBarImage forBarMetrics:UIBarMetricsDefault];

I'm trying to add an option in my app to change the background image of the navbar when a switch is toggled, however it does not seem to work. Is it only possible to set the background image when the app launches? How can I do this after the app has already launched?

This is the code I have:

- (void) switchChanged:(id)sender {
    UISwitch* switchView = sender;

        if (switchView.isOn) {
            UIImage *navBarImage = [UIImage imageNamed:@"black_nav.png"];
            [[UINavigationBar appearance] setBackgroundImage: navBarImage forBarMetrics:UIBarMetricsDefault];
        }
        else {
            UIImage *navBarImage = [UIImage imageNamed:@"white_nav.png"];
            [[UINavigationBar appearance] setBackgroundImage: navBarImage forBarMetrics:UIBarMetricsDefault];
        }
}
like image 630
James Avatar asked Nov 24 '25 03:11

James


1 Answers

Use setBackgroundImage:forBarMetrics: method:

[navbar setBackgroundImage:[UIImage imageNamed:@"navbar"] 
               forBarMetrics:UIBarMetricsDefault];
like image 131
Dennis Pashkov Avatar answered Nov 25 '25 18:11

Dennis Pashkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!