深入理解iOS的状态栏

2020-01-18 16:13:32王振洲
preferredStatusBarStyle方法重绘状态栏的样式

childViewControllerForStatusBarStyle函数


// Override to return a child view controller or nil. If non-nil, that view controller's status bar appearance attributes will be used. If nil, self is used. Whenever the return values from these methods change, -setNeedsUpdatedStatusBarAttributes should be called.
- (nullable UIViewController *)childViewControllerForStatusBarStyle 
NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED;

这个函数的返回值默认返回nil,此时系统就会调用当前viewControllerApreferredStatusBarStyle函数;如果返回值是另一个viewControllerB那么系统就会调用viewControllerBpreferredStatusBarStyle函数。

运用这个函数就可以解决嵌套UINavigationController设置样式无效的问题。

解释一下为什么嵌套UINavigationControllerviewControllerpreferredStatusBarStyle函数设置无效:

在我们嵌套了UINavigationController的时候,我们的AppDelegate.window.rootViewController通常是我们创建的navigationController,这时首先会调用的是navigationController中的childViewControllerForStatusBarStyle函数,因为默认返回nil,那么接下来就会调用navigationController本身的preferredStatusBarStyle函数,所以我们在viewController中通过preferredStatusBarStyle函数设置的状态栏样式就不会被调用发现,所以也就无效了。

所以我们要自己创建一个继承于UINavigationcontrollerNavigationController,在这个子类中重写childViewControllerForStatusBarStyle函数


- (UIViewController *)childViewControllerForStatusBarStyle{
  return self.topViewController;
}

这样navigationController中的childViewControllerForStatusBarStyle函数会返回navigationController中最上层的viewController,那么viewController中的preferredStatusBarStyle函数的设置就会被系统获知

childViewControllerForStatusBarHidden函数


- (nullable UIViewController *)childViewControllerForStatusBarHidden 

NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED;

childViewControllerForStatusBarHidden函数的使用原理同上,不再赘述。

preferredStatusBarUpdateAnimation函数


// Override to return the type of animation that should be used for status bar changes for this view controller. This currently only affects changes to prefersStatusBarHidden.
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation 
NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED; // Defaults to UIStatusBarAnimationFade