美文网首页
iOS-覆盖statusBar,而不是隐藏

iOS-覆盖statusBar,而不是隐藏

作者: oneYing | 来源:发表于2016-12-21 23:36 被阅读1438次

    有时候你想隐藏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}};

    • (instancetype)newWindow{
      WYXWindow *newWin = [[WYXWindow alloc] initWithFrame:frame];
      if (newWin) {
      newWin.windowLevel = UIWindowLevelAlert -2;
      newWin.backgroundColor = [UIColor redColor];
      [newWin makeKeyAndVisible];
      }
      return newWin;
      }
      @end```
      在需要的时候调用
    - (void)viewDidAppear:(BOOL)animated{
        [super viewDidAppear:animated];
        // 因为当前viewcontroller 是 rootController,所以调用该方法要在viewDidAppear:方法中
        // 不然在appdelegate中设置的rootController就会失效
        // 如果不是在rootController,则在 viewDidLoad 中调用即可
         [self hideStatusBarWithWindow];
    }
    
    // 自定义window来覆盖statusbar
    - (void)hideStatusBarWithWindow{
        wind = [WYXWindow newWindow];
    }
    

    原码地址

    相关文章

      网友评论

          本文标题:iOS-覆盖statusBar,而不是隐藏

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