Setting of UIWindow and statusbar in iOS

  • 2021-11-14 07:19:25
  • OfStack

Recently, when doing development, we should do a control similar to UIAlertView. The practice is to create a class based on UIView, and customize the control settings in it. In order to imitate UIAlertView as much as possible, we created a new UIWindow in this class and displayed self on this window.

Because the content of statusbar in app is white, the newly created window will change the state of statusbar, and can't get the result we want. In order to avoid other errors in Series 1, the color of statusbar is used

- (UIStatusBarStyle)preferredStatusBarStyle​
- (void)setNeedsStatusBarAppearanceUpdate​

These two methods, you are not mistaken, these two methods are UIViewController methods, so what is the relationship with UIView? Yes, here we want to set rootViewController for UIWindow, write these two methods in this rootViewController and do some other settings, so that the control can be displayed in rootViewController, and statusbar is also the state we want.

On the code (demo partial code):

// TestView.h
@interface TestView : UIView
@property (nonatomic, strong) NSString *clickTitle;​
- (void)show;
// TestView.m
​#import "TestView.h"
@implementation TestView
  UIWindow *window;
  UIButton *clickBtn;
- (void)makeWindow
  window = [[UIWindow alloc] init];
  window.windowLevel = UIWindowLevelStatusBar + 1;
  window.backgroundColor = [UIColor clearColor];
  [window makeKeyAndVisible];
  TestVC *rootVC = [[TestVCalloc] init];
  rootVC.view.backgroundColor = [UIColorcolorWithRed:0green:0blue:0alpha:0.5];
  UINavigationController *navi = [[UINavigationControlleralloc]initWithRootViewController:rootVC];
  window.rootViewController = navi;
  navi.navigationBarHidden = YES;
  self.frame = CGRectMake(0, 0, window.frame.size.width - 40, 80); =;
  [rootVC.view addSubview:self];
- (instancetype)initWithFrame:(CGRect)frame
  if (self = [super initWithFrame:frame]) {
    clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
- (NSString *)clickTitle
  if (!_clickTitle) {
    _clickTitle = @"clicks";
- (void)show
  [clickBtn setTitle:self.clickTitleforState:UIControlStateNormal];
// TestVC.m
#import "TestVC.h"
@interfaceTestVC ()
@implementation TestVC
- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.
  [self setNeedsStatusBarAppearanceUpdate];
- (UIStatusBarStyle)preferredStatusBarStyle
  return UIStatusBarStyleLightContent;

The code is very simple, but I want to achieve this effect for a long time, feeling that there will be a simpler way, and continue to study later.

Related articles: