Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I animate UINavigationBar setBackgroundImage: forBarMetrics:?

I am changing the background image of the navigation bar when a certain controller is pushed. I want to animate that change. I can do so with the following code:

[UIView transitionWithView:self.navigationController.navigationBar
                  duration:0.3f
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"now-playing-nav-bar.png"]
                                                 forBarMetrics:UIBarMetricsDefault];
} completion:NULL];

However, this blocks the default push animation applied to the navigationBarTitle and UIBarButtonItems.

How do I get the background change and the push animations to work together?

I would prefer as vanilla a solution as possible.

PS: I can't use tintColor because the background is textured.

like image 633
duci9y Avatar asked Jan 30 '13 11:01

duci9y


1 Answers

Tested only on iOS 6

I solved it using Core Animation:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    CATransition *animation = [CATransition animation];
    animation.duration = 0.3;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionFade;

    [self.navigationController.navigationBar.layer addAnimation:animation forKey:nil];

    [UIView animateWithDuration:0.3 animations:^{
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"now-playing-nav-bar.png"] forBarMetrics:UIBarMetricsDefault];
    }];
}

Do the same in viewWillDisappear: and you are good to go.

like image 81
duci9y Avatar answered Oct 28 '22 07:10

duci9y