Ios: Modify the background color of NavigationController
During ios development, we often need to modify the background color of NavigationController. When using [self. navigationController. when navigationBar setBackgroundColor: [UIColor redColor], the running result cannot be changed to Beijing color:
A new method is provided to solve this problem:
Write a NavigationBar to write a category:
@ Interface UINavigationBar (BackgroundColor)
// Set the background color of navigationBar
-(Void) lt_setBackgroundColor :( UIColor *) backgroundColor;
@ End
@ Implementation UINavigationBar (BackgroundColor)
Static char overlayKey;
-(UIView *) overlay
{
Return objc_getAssociatedObject (self, & overlayKey );
}
-(Void) setOverlay :( UIView *) overlay
{
Objc_setAssociatedObject (self, & overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC );
}
-(Void) lt_setBackgroundColor :( UIColor *) backgroundColor
{
If (! Self. overlay ){
[Self setBackgroundImage: [UIImage new] forBarMetrics: UIBarMetricsDefault];
[Self setShadowImage: [UIImage new]; // insert an overlay into the view hierarchy
Self. overlay = [[UIView alloc] initWithFrame: CGRectMake (0,-20, [UIScreen mainScreen]. bounds. size. width, 64)];
[Self insertSubview: self. overlay atIndex: 0];
}
Self. overlay. backgroundColor = backgroundColor;
}
@ End
Note: When Using objc_getAssociatedObject, You need to introduce the header file # import