Reputation: 509
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];
}
}
Upvotes: 3
Views: 3266
Reputation: 1376
Try this one
// Create resizable images
UIImage *gradientImage44 = [[UIImage imageNamed:@"surf_gradient_textured_44"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
UIImage *gradientImage32 = [[UIImage imageNamed:@"surf_gradient_textured_32"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
// Set the background image for all UINavigationBars
[[UINavigationBar appearance] setBackgroundImage:gradientImage44 forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundImage:gradientImage32 forBarMetrics:UIBarMetricsLandscapePhone];
Upvotes: 0
Reputation: 288
You can replace the default in each view doing this:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,
self.navigationController.navigationBar.frame.size.width,
self.navigationController.navigationBar.frame.size.height)];
[imageView setImage:[UIImage imageNamed:@"newImage.png"]];
[self.navigationController.navigationBar addSubview:imageView];
[self.navigationController.navigationBar sendSubviewToBack:imageView];
Upvotes: 3
Reputation: 944
Use setBackgroundImage:forBarMetrics:
method:
[navbar setBackgroundImage:[UIImage imageNamed:@"navbar"]
forBarMetrics:UIBarMetricsDefault];
Upvotes: 6