Jacob Jacob - 5 months ago 36
iOS Question

Transition Navigation Bar Title

In an app called "Luvocracy" the title of the navigation bar is changed when the user swipes up on the screen. The old title is pushed up, while the new one is transitioned in. I don't have a video of it now, but here are some screen shots:

https://www.dropbox.com/s/sns0bsxkdv7pw3l/Photo%20Apr%2008%2C%2011%2001%2005%20AM.png

https://www.dropbox.com/s/ys9a49u3dyxrlcm/Photo%20Apr%2008%2C%2011%2001%2009%20AM.png

https://www.dropbox.com/s/dlcfvfvqqov3ag7/Photo%20Apr%2008%2C%2011%2001%2013%20AM.png

How can I animate or transition in a new navigation bar title as shown?

Edit: The app is no longer available on the app store so I am unable to upload a video of this action.

Answer

You can animate the title changing by using a CATransition... however, because the title itself is a private property on the navigation bar, you need to first create a custom label and attach that to the navigation item.

Setup the title label (this would override the default navigation bar's title):

UILabel *titleLabelView = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 44.0f) /* auto-sized anyway */];
titleLabelView.backgroundColor = [UIColor clearColor];
titleLabelView.textAlignment = NSTextAlignmentCenter;
titleLabelView.textColor = [UIColor blackColor];
titleLabelView.font = [UIFont systemFontOfSize:16.0f];
titleLabelView.adjustsFontSizeToFitWidth = YES;
titleLabelView.text = @"@cracy123";
self.navigationItem.titleView = titleLabelView;

Then whenever you want to animate the title changing (assume on a scroll view delegate action), add a CAAnimation layer and presto:

CATransition *animation = [CATransition animation];
animation.duration = 1.0;
animation.type = kCATransitionPush;
animation.subtype = kCATransitionFromTop;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[self.navigationItem.titleView.layer addAnimation:animation forKey:@"changeTitle"];

((UILabel*)self.navigationItem.titleView).text = @"JACOB K";

You can obviously change the CATransition animation properties to get the effect you're after, but those will give you the 'push-up' effect.

enter image description here

Comments