为什么我不能隐藏状态栏?

时间:2023-01-17 14:30:29

I use the following line of code to hide the status bar:

我使用以下代码行来隐藏状态栏:

view.window?.windowLevel = UIWindowLevelStatusBar

view.window?.windowLevel = UIWindowLevelStatusBar

What is surprising me is that this line of code does not work from within any of the "life cycle" methods of the view: viewDidLoad(), viewWillAppear(:). However, when I create a button and hook it up to an action method the code above works perfectly and hides the status bar behind the window. I want to be able to call view.window?.windowLevel = UIWindowLevelStatusBar in viewDidLoad(). Can anyone please help me understand why it does not work from within the mentioned view "life cycle" methods?

让我感到惊讶的是,这行代码不适用于视图的任何“生命周期”方法:viewDidLoad(),viewWillAppear(:)。但是,当我创建一个按钮并将其连接到一个动作方法时,上面的代码完美地工作并隐藏窗口后面的状态栏。我希望能够在viewDidLoad()中调用view.window?.windowLevel = UIWindowLevelStatusBar。任何人都可以帮助我理解为什么它不能在上面提到的“生命周期”方法中起作用?

3 个解决方案

#1


1  

Neither in viewDidLoad nor viewWillAppear the view controller is in the view hierarchy, therefore view.window is nil.

在viewDidLoad和viewWillAppear中,视图控制器都不在视图层次结构中,因此view.window为nil。

You might work around that by using viewDidAppear or access the window using UIApplication.shared.delegate.window instead.

您可以使用viewDidAppear解决这个问题,或者使用UIApplication.shared.delegate.window访问该窗口。

In general it's not a good idea to change the level of the main window though.

一般来说,改变主窗口的级别并不是一个好主意。

#2


0  

Your ViewController will only be able to adjust the status bar if you set View controller-based status bar appearance to YES in your info.plist. Otherwise it is set by global parameters in your plist or proj file.

如果在info.plist中将基于View控制器的状态栏外观设置为YES,则ViewController将只能调整状态栏。否则,它由plist或proj文件中的全局参数设置。

#3


0  

If you only wanted to hide status bar use:

如果您只想隐藏状态栏使用:

    [[UIApplication sharedApplication] setStatusBarHidden:YES]

#1


1  

Neither in viewDidLoad nor viewWillAppear the view controller is in the view hierarchy, therefore view.window is nil.

在viewDidLoad和viewWillAppear中,视图控制器都不在视图层次结构中,因此view.window为nil。

You might work around that by using viewDidAppear or access the window using UIApplication.shared.delegate.window instead.

您可以使用viewDidAppear解决这个问题,或者使用UIApplication.shared.delegate.window访问该窗口。

In general it's not a good idea to change the level of the main window though.

一般来说,改变主窗口的级别并不是一个好主意。

#2


0  

Your ViewController will only be able to adjust the status bar if you set View controller-based status bar appearance to YES in your info.plist. Otherwise it is set by global parameters in your plist or proj file.

如果在info.plist中将基于View控制器的状态栏外观设置为YES,则ViewController将只能调整状态栏。否则,它由plist或proj文件中的全局参数设置。

#3


0  

If you only wanted to hide status bar use:

如果您只想隐藏状态栏使用:

    [[UIApplication sharedApplication] setStatusBarHidden:YES]