How to prevent status bar from overlapping content

2019-01-10 09:52发布

I'm trying to use the new feature added in iOS 8 - hiding the navigation bar while user is scrolling the table view (similar to what mobile Safari does). I'm setting the property hidesBarsOnSwipe of UINavigationController to YES in viewDidAppear method of UITableViewController:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if([self.navigationController respondsToSelector:@selector(hidesBarsOnSwipe)]) {
        self.navigationController.hidesBarsOnSwipe = YES;
    }
}

The navigation bar hides when the view is being scrolled. So far so good. But the status bar is still visible and my table view contents show through it, which looks ugly:

enter image description here

I tried setting edgesForExtendedLayout to UIEdgeRectNone or adjusting the contentInset of the table view, but it didn't help. Is there any other solution to hide the status bar along with the navigation bar, or make it opaque?

9条回答
Luminary・发光体
2楼-- · 2019-01-10 10:34

That new property comes with its barHideOnSwipeGestureRecognizer.

From the UINavigationController Class Reference:

You can make changes to the gesture recognizer as needed but must not change its delegate and you must not remove the default target object and action that come configured with it. Do not try to replace this gesture recognizer by overriding the property.

But you can add a target:

[self.navigationController setHidesBarsOnSwipe:YES];
[self.navigationController.barHideOnSwipeGestureRecognizer addTarget:self action:@selector(swipeGesture:)];

... and do whatever you want in the callback:

- (void)swipeGesture:(UIPanGestureRecognizer*)gesture
{
    // Tweak the status bar
}

You might have to manually switch on the gesture states, figure out when to hide/show the status bar, etc. Hope that helps!

查看更多
Anthone
3楼-- · 2019-01-10 10:35

If you want to hide status bar with animation:

override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
    return .Slide
}

override func prefersStatusBarHidden() -> Bool {
    return navigationController?.navigationBarHidden ?? false
}
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-10 10:37

Another way to do it is just add another view (above the tableview or collectionview or webview or scrollview or whatever) and set the view's top constraint to "Superview.Top" and its bottom constraint to "Top Layout Guide.Bottom" ,set the view's background color and thats it , you can even do it all in Interface Builder without any code. And if you want to respond to that event you can add a keypath observer to the view's bounds change , or subclass the view and override its bounds setter...

查看更多
登录 后发表回答