Programatically Hiding Status Bar When Adding New UIWindow?

試著忘記壹切 提交于 2019-12-10 17:44:18

问题


I'm currently adding a new UIWindow to my app when displaying my own custom alert.

Before adding this UIWindow my app had the status bar hidden, but now it is visible. How can I hide the status bar programatically in this new window. I've tried everything but it doesn't work.

This is how I add my UIWindow:

notificationWindow = [[UIWindow alloc] initWithFrame: CGRectMake(0, 0, 1.0, 1.0)];

notificationWindow.backgroundColor = [UIColor clearColor]; // your color if needed
notificationWindow.userInteractionEnabled = NO; // if needed

// IMPORTANT PART!
notificationWindow.windowLevel = UIWindowLevelAlert + 1;

notificationWindow.rootViewController = [UIViewController new];
notificationWindow.hidden = NO; // This is also important!
[notificationWindow addSubview:confettiView];

回答1:


Your notificationWindow has a rootViewController. Therefore implement Custom UIViewController as rootViewController with preferStatusBarHidden method as

- (BOOL)prefersStatusBarHidden {
  return YES;
}

instread of using default UIViewController instance [UIViewController new].




回答2:


Essentially, since each UIWindow is independent of each other, you need to tell each one that you create what your preference is for the status bar.

In order to do this programmatically, you have to create a faux controller with your given preference so that when you unhide the new UIWindow, the status bar doesn't show/hide or flash on the screen.

class FauxRootController: UIViewController {

    // We effectively need a way of hiding the status bar for this new window
    // so we have to set a faux root controller with this preference
    override func prefersStatusBarHidden() -> Bool {
        return true
    }

}

and the implementation would look like:

lazy private var overlayWindow: UIWindow = {
    let window = UIWindow.init(frame: UIScreen.mainScreen().bounds)
    window.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
    window.backgroundColor = UIColor.clearColor()
    window.windowLevel = UIWindowLevelStatusBar
    window.rootViewController = FauxRootController()
    return window
}()



回答3:


Swift 4.2 Answer

Create a ViewController class:

class NoStatusBarViewController: UIViewController {    

    override var prefersStatusBarHidden: Bool {

        return true

    }

}

And in your UIWindow class:

rootViewController = NoStatusBarViewController()



回答4:


You can use UIAlertController instead of UIAlertView.

notificationWindow.windowLevel = UIWindowLevelNormal;


来源:https://stackoverflow.com/questions/23151191/programatically-hiding-status-bar-when-adding-new-uiwindow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!