Adjusting views when Status Bar hides on rotation

2020-03-05 03:29发布

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!

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.

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.

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.

1条回答
太酷不给撩
2楼-- · 2020-03-05 04:08

The correct approach is:

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

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

  • 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).

  • 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.

enter image description here enter image description here enter image description here

查看更多
登录 后发表回答