[IOS] Set the color of the NavigationBar

Reprinted from: http://www.jianshu.com/p/d0c2ce8f0318?utm_campaign=maleskine&utm_content=note&utm_medium=reader_share&utm_source=weibo

 

When developing an APP, in order to make the APP more beautiful, a color is often set for the NavigationBar. If you directly set a color for the navigationBar,

self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];

You will find that the effect cannot be achieved at all, and the displayed color is not the set color at all. This is because of the transparency of the navigation setting of the system.
How can you achieve the desired effect? ​​You need a picture, and then set its picture. it's ok

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navibar_white"] forBarMetrics:(UIBarMetricsDefault)];

 

*After testing, it is found that the above two methods of IOS9 have the same effect.

 

If you say that it is too troublesome to need a picture, then you can add a category color to UIImage

@interface UIImage (Color)
/**
 *  @brief  根据颜色生成纯色图片
 *
 *  @param color 颜色
 *
 *  @return 纯色图片
 */
@end

@implementation UIImage (Color)
/**
 *  @brief  根据颜色生成纯色图片
 *
 *  @param color 颜色
 *
 *  @return 纯色图片
 */
+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}
@end

Code doesn't need pictures

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forBarMetrics:(UIBarMetricsDefault)];

In the future, if you need a solid-color picture, you can generate it yourself.
For example, when we use a button, we will set different color values ​​for the button in different states, saving the trouble of asking for pictures for the UI.

[self.codeButton setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:(UIControlStateNormal)];
    [self.codeButton setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:(UIControlStateDisabled)];
    [self.codeButton setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor] forState:(UIControlStateHighlighted)];

Do you have the normal color, the color you press, and the color when you can't press it?
How can you make the button not press? Just one sentence

self.codeButton.enabled = NO;

Is it much more convenient?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326223599&siteId=291194637