How to customize UINavigationBar animation setBackgroundImage: forBarMetrics :?

I change the background image of the navigation bar when I click on a specific controller. I want to bring this change to life. I can do this 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 navigationBarTitle and UIBarButtonItem s.

How do I get background change and push animation for collaboration?

I would rather have a vanilla solution possible.

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

+8
ios objective-c ios6 uinavigationcontroller
source share
3 answers

Tested only on iOS 6

I solved this with 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're good to go.

+24
source share

This works for me on iOS 9:

 override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) changeNavigationBackground() } func changeNavigationBackground() { // navigationBar should always exist if the view controller is in a UINavigationController guard let navigationBar = navigationController?.navigationBar else { return } // the current navigation background guard let imageView = navigationBar.subviews.filter({ $0 is UIImageView }).first else { return } let image = UIImage(named: "navigation_background") let newImageView = UIImageView(image: image) newImageView.frame = imageView.frame newImageView.alpha = 0.0 navigationBar.insertSubview(newImageView, belowSubview: imageView) transitionCoordinator()?.animateAlongsideTransition({ (context) in imageView.alpha = 0.0 newImageView.alpha = 1.0 }, completion: { (context) in newImageView.removeFromSuperview() navigationBar.setBackgroundImage(image, forBarMetrics: .Default) imageView.alpha = 1.0 }) } 

I try to avoid Core Animation if possible, so I only used the views and changed their alpha values ​​along with the transition.

+5
source share

Does push animation work or not without transition animation? If so, maybe you need to do the push animation yourself in the image-changing section of the navigation bar.

0
source share

All Articles