美文网首页
iOS状态栏简单设置

iOS状态栏简单设置

作者: 陈木舟 | 来源:发表于2016-10-31 16:52 被阅读66次

知识普及

苹果各机型的状态栏高度为固定的20个像素,状态栏分为前景和背景两部分:

  • 前景就是状态栏显示的字体、运营商、电量等内容,
  • 背景是前景后面显示的纯色部分。

我项目中需求:特定的UIViewController中显示不同状态栏的颜色,主要用到两种状态:

  • 前景色为白色,背景色为黑色


  • 前景色为黑色,背景色为白色


改变前景

上面两种状态的前景分别对应下面两种类型

typedef NS_ENUM(NSInteger, UIStatusBarStyle) {
    UIStatusBarStyleDefault           = 0, //默认模式,前景内容为黑色,用在亮色背景上
    UIStatusBarStyleLightContent      = 1, //前景内容为白色,用在暗色背景上
}

由于不同的页面显示类型不一样,所以不能全局设置,我们需要在不同的UIViewController中设置对应的颜色,首先说一下思路,在viewWillAppear方法中设置当前 UIViewController 的状态栏颜色,在viewWillDisappear恢复默认的状态栏颜色,当然这里并不是项目中的每个页面都需要更改状态栏颜色,我们会有一个默认的状态栏颜色。下面是具体步骤:

  1. 在info.plist中添加View controller-based status bar appearance并设置为NO
  2. 在UIViewController对应方法中添加对应内容,如下
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //改变状态栏字体和背景颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    //恢复状态栏字体和背景颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

当然这里我们只改变了前景颜色,当背景为黑色时我们将前景也改为UIStatusBarStyleDefault将什么都看不到。所以我们在更改时,需要前景和背景一起改,继续往下看。

改变背景

背景颜色的改变使用的是KVC方式,直接上代码

//改变状态栏背景颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

setStatusBarBackgroundColor的参数color就是需要设置的颜色,所以上面UIViewController中对应的方法改为

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //改变状态栏字体和背景颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];//前景
    [self setStatusBarBackgroundColor:[UIColor blackColor]];//背景
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    //恢复状态栏字体和背景颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];//前景
    [self setStatusBarBackgroundColor:[UIColor whiteColor]];//背景
}

这里只是根据需求简单的设置了状态栏的类型,没有涉及状态更多的内容和原理。如有问题望多指教。

相关文章

网友评论

      本文标题:iOS状态栏简单设置

      本文链接:https://www.haomeiwen.com/subject/yldputtx.html