Animating the UINavigationBar from a solid colour to a transparent colour

850 views Asked by At

I am trying to animate the navigation bar of this app from a solid colour to a transparent colour during a transition.

The barStyle and translucent properties also change for the new view controller.

The reason I do this is because we use a transparent nav bar and fade it in during scrolling...

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat maxY = self.headerHeight - 64;

    CGFloat percentage = MIN(0.996, MAX(0, [self alphaFromPercentageWithEasing:offsetY / maxY]));

    [self.navigationController.navigationBar setBackgroundImage:[UIColor imageFromColor:self.themeColor alpha:percentage] forBarMetrics:UIBarMetricsDefault];
}

This works fine when scrolling but in order to get a transparent navigation bar you have to use the backgroundImage property of the navigationBar. If you try to use a colour with alpha less than 1 then the colour is used with alpha of 1. So you can't just use a transparent colour.

The problem I have is that during the transition I have the transitionCoordinator doing this...

[self.transitionCoordinator
 animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
      self.navigationController.navigationBar.barTintColor = self.themeColor;
 }
 completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
     // this is so that when popping back to here the bar alpha
     // is set correctly from the current scroll position
     [self scrollViewDidScroll:self.tableView];
 }];

Obviously, this will animate the colour from the original colour to the view controller's themeColor property with 100% alpha and then when the transition finishes the navigationBar just disappears.

I have even tried animating between images...

[self.navigationController.navigationBar setBackgroundImage:[UIColor imageFromColor:originalColor alpha:1.0] forBarMetrics:UIBarMetricsDefault];

[self.transitionCoordinator
 animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
     [self.navigationController.navigationBar setBackgroundImage:[UIColor imageFromColor:self.themeColor alpha:0] forBarMetrics:UIBarMetricsDefault];
 }
 completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
     // this is so that when popping back to here the bar alpha
     // is set correctly from the current scroll position
     [self scrollViewDidScroll:self.tableView];
 }];

but this just sets it to the final image with 0% alpha without animation.

I'm looking for a way to animate from 100% alpha of the original colour to 0% alpha of the themeColor during the transition. So the bar will animate both from (for example) blue to red and 1.0 alpha to 0.0 alpha.

Is this even possible? Anyone know how?

0

There are 0 answers