问题
I have a standard Master-Detail Application, and I'm trying to conditionally show/hide the status bar.
Overriding prefersStatusBarHidden()
in MasterViewController does nothing. It never even gets called.
override func prefersStatusBarHidden() -> Bool {
return true
}
Setting UIViewControllerBasedStatusBarAppearance
in Info.plist doesn't help, presumably since YES
is already the default value. Calling setNeedsStatusBarAppearanceUpdate()
doesn't help either.
I am targeting iOS 9.
回答1:
There is a little bit cleaner solution. There is a function childViewControllerForStatusBarHidden
which is specifically designed to return a child view controller to which prefersStatusBarHidden should be forwarded.
So, it will be better to override it. It will look like this:
override func childViewControllerForStatusBarHidden() -> UIViewController? {
if var topViewController = self.viewControllers.first {
if let navigationController = topViewController as? UINavigationController {
topViewController = navigationController.topViewController!
}
return topViewController
}
return super.childViewControllerForStatusBarHidden()
}
And probably you can even omit following. NavigationViewController has childViewControllerForStatusBarHidden() on it's own which will send it to child viewcontroller.
if let navigationController = topViewController as? UINavigationController {
topViewController = navigationController.topViewController!
}
回答2:
The answer is to override prefersStatusBarHidden()
starting from the window's root view controller. In a Master-Detail Application, this requires subclassing UISplitViewController
to forward the message down the view controller hierarchy.
Something like this:
override func prefersStatusBarHidden() -> Bool {
if var topViewController = self.viewControllers.first {
if let navigationController = topViewController as? UINavigationController {
topViewController = navigationController.topViewController!
}
return topViewController.prefersStatusBarHidden()
}
return super.prefersStatusBarHidden()
}
回答3:
If you're fine doing it for all your split view controllers, this works for me:
extension UISplitViewController {
override open var childForStatusBarHidden: UIViewController? {
return (viewControllers.last as? UINavigationController)?.visibleViewController
}
}
来源:https://stackoverflow.com/questions/35670767/prefersstatusbarhidden-isnt-getting-called