iOS-覆盖statusBar,而不是隐藏

2016-12-21  本文已影响1438人  oneYing

有时候你想隐藏statusBar,然后在statusbar的位置做些自己的事情,但这时viewContoller的view的frame会发生变化(上移)。这时就可以覆盖statusBar。
一般的view即使add到Window上,也还是会被statusBar覆盖的。

有两种方法:
第一种,拿到statusBar。
系统并没有给出获取statusBar的API,所以就要走不寻常的路子了--KVC。

// 以KVC的方式来获取statusBar,你会发现其也应该是继承自UIView
- (void)hideStautsBarWithGetStatusBar{
    // 你可以试着打印statusBar及基父类的类型
    //    id statusBar = [[UIApplication sharedApplication] valueForKey:@"statusBar"];
    //    NSLog(@"%@--%@",statusBar,[statusBar superclass]);
    UIView  *statusBar = [[UIApplication sharedApplication] valueForKey:@"statusBar"];
    UIView *newView = [[UIView alloc] initWithFrame:statusBar.frame];
    newView.backgroundColor = [UIColor yellowColor];
    [statusBar addSubview:newView];
}

再一种就是自定义window

#import <UIKit/UIKit.h>

@interface WYXWindow : UIWindow

+ (instancetype)newWindow;

@end```
具体实现

@implementation WYXWindow
static const CGRect frame = {{0, 0}, {320, 20}};

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 因为当前viewcontroller 是 rootController,所以调用该方法要在viewDidAppear:方法中
    // 不然在appdelegate中设置的rootController就会失效
    // 如果不是在rootController,则在 viewDidLoad 中调用即可
     [self hideStatusBarWithWindow];
}

// 自定义window来覆盖statusbar
- (void)hideStatusBarWithWindow{
    wind = [WYXWindow newWindow];
}

原码地址

上一篇下一篇

猜你喜欢

热点阅读