旋转隐藏状态栏时调整视图

旋转隐藏状态栏时调整视图

问题描述:

我一直在四处寻找答案,但是我只发现有类似问题的人,而没有这个确切的问题,所以希望这里有人可以帮助我!

I've browsed around looking for an answer for this, but I've only found people with similar problems and not this exact problem, so hopefully someone here can help me!

我有一个iPad应用程序.在iPad上,当您纵向或横向握住iPad时,始终会显示带有时钟和电池的状态栏.因此,我的一些View Controller顶部有一些自定义工具栏,它们占了这20点.

I have an iPad App. On iPad, when you hold the iPad in either portrait or landscape, the status bar with the clock and battery is always shown. For this reason, I have some custom toolbars at the top of some of my View Controllers that account for those 20 points.

我正在努力使我的应用程序通用.我注意到的第一件事是,当iPhone在纵向模式下处于帮助状态时,会显示状态栏,但是在横向模式下握住它时,状态栏会隐藏起来,现在我的工具栏太高了20点.

I am now working on making my App universal. The first thing I noticed is that when the iPhone is help in portrait mode the status bar is shown, but when it's held in landscape mode, the status bar hides and now I have a toolbar that is 20 points too tall.

我对始终隐藏或始终显示状态栏不感兴趣.我认为将其隐藏在手机的横向模式下的功能还不错.我想做的就是能够检测到何时隐藏状态栏,以便可以调整工具栏的Y位置(将其设置为0或-20).更好的解决方案是,如果我有办法设置布局约束来处理这种情况.

I am not interested in either always hiding or always showing the status bar. I think the functionality of hiding it on landscape mode on the phone is fine. What I want to do is to be able to detect when the status bar is hidden so that I can adjust the Y position of my toolbar (so make it either 0 or -20). An even better solution would be if there's a way for me to set my layout constraints to handle this scenario.

正确的方法是:

  • 使用具有正常高度的普通工具栏-请勿在高度上设置任何约束.

  • Use a normal toolbar with a normal height - do not set any constraint on the height.

在超级视图(非超级视图边距)上添加前导约束0,在超级视图(非超级视图边距)后添加约束0.

Add leading constraint 0 to superview (not superview margin), trailing constraint 0 to superview (not superview margin).

在顶部布局指南(或安全区域的顶部)中添加顶部约束0.这似乎会在工具栏上方留出20个像素的空间,但会发出恶笑并继续进行操作.

Add top constraint 0 to top layout guide (or top of safe area). This will appear to leave 20 pixels of space above the toolbar, but laugh an evil laugh and proceed.

将视图控制器设置为工具栏的委托(为此目的,有一个委托出口).

Set the view controller as the toolbar's delegate (there is a delegate outlet for this purpose).

让视图控制器采用UIBarPositioningDelegate并实现委托方法,如下所示:

Have the view controller adopt UIBarPositioningDelegate and implement the delegate method as follows:

class ViewController: UIViewController, UIBarPositioningDelegate {
    func position(for bar: UIBarPositioning) -> UIBarPosition {
        return .topAttached
    }
}

这将导致在有状态栏时工具栏的外观高度在状态栏后面向上扩展,但是在没有状态栏的情况下它将具有正常的高度,并且会向顶部打击.

This will cause the apparent height of the toolbar to be extended up behind the status bar when there is a status bar, but it will have normal height and be smack against the top when there is no status bar.