简体   繁体   中英

How to update the status bar style when transitioning to a new view controller?

I have a container view controller which transitions from one child view controller to another child using this code:

- (void)switchToNewViewController:(UIViewController *)newController {
  [self 
    transitionFromViewController:self.currentViewController 
    toViewController:newController
    duration: 0.6
    options:UIViewAnimationOptionTransitionFlipFromLeft
    animations:^{
      newController.view.frame = self.currentViewController.view.frame;
    }
    completion:^(BOOL finished) {
      [self.currentViewController removeFromParentViewController];
      [newController didMoveToParentViewController:self];
      self.currentViewController = newController;
    }
  ];
}

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

I have a problem when the first view controller prefers dark text in the status bar but the next view controller prefers light text.

First view controller:

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}

Second view controller:

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

I put a breakpoint in both the first and second view controller's preferredStatusBarStyle. The debugger only breaks on the first view controller, but does not on the second view controller. As a result, the status bar style doesn't change. How would I notify the Cocoa framework that it needs to read the second view controller's preference?

Ensure that UIViewControllerBasedStatusBarAppearance is set to YES in your Info.plist file. This should ensure that the preferredStatusBarStyle is called per view controller.

Failing that, set the above plist key to NO , then add the following to viewWillAppear in each of your UIViewController's implementation files:

if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) { [self setNeedsStatusBarAppearanceUpdate]; }

You will need to ensure that this is implemented in every view controller in which you need to update the appearance of the status bar.

If all else fails

Call the following from wherever you want to update the status bar style:

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

Obviously replacing the style with your desired status bar style.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM