prefersStatusBarHidden isn't getting called

风流意气都作罢 提交于 2019-12-05 02:29:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!