UINavigationBar with solid color iOS 5

安稳与你 提交于 2019-12-04 13:20:06

In iOS 5 you can use the UIAppearance protocol to set the appearance of all UINavigationBars in your app. Reference: link.

The way I got a solid color was to create a custom image for the navigation bar, and set it as UINavigationBars background. You might have to create the image with the same size as the UINavigationBar, at least that's what I did.

In your app delegate, do something like this:

UIImage *image = [UIImage imageNamed:@"navbarbg.png"];
[[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];

You also have to add the UIAppearanceContainer protocol to the header file:

@interface AppDelegate : UIResponder <UIApplicationDelegate, UIAppearanceContainer>

@end

You can probably achieve the same thing by setting some color or something, instead of an image. But I found this to be an easy solution.

This covers both iOS 5 and iOS 4.3 and earlier

https://gist.github.com/1774444

zyzzyxx

This is more of a hack and has consistently worked for me. This needs to be in the AppDelegate file.

//Create  a size struct.
CGSize size = CGSizeMake(768, 50);

//CReate a imagecontext from a non-existing image. You can use a existing image as well, in that case the color will be the color of the image. 
UIImage *backgroundImage = [UIImage imageNamed:@"nonexist.png"];

UIGraphicsBeginImageContext(size);

[backgroundImage drawInRect:CGRectMake(0,0,size.width,size.height)];

UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

self.navigationController = [[UINavigationController alloc]initWithRootViewController:self.viewController];

Set the background color to be the color of your choice.

[self.navigationController.view setBackgroundColor:[UIColor blackColor]];

self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];

//Most important line.
[navigationController.navigationBar setBackgroundImage: newImage forBarMetrics:UIBarMetricsDefault];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!