How to animate UISearchBar like in Contacts

Ever seen the animation that occurs when you tap in the search bar in Contacts? The navigation bar slides upwards, the search bar goes up and replaces it, and the Cancel button comes in from the left.

Here’s a before and after:

before animation after animation

Now, how is that done?

The first question is how to animate the Navigation Bar out of the way. This can be done with a simple frame animation as follows:

CGRect frame = self.navigationController.view.frame;
frame.origin.y -= navbarHeight;
frame.size.height += navbarHeight;
[UIView animateWithDuration:duration animations:^(){
self.navigationController.view.frame = frame;

This also moves your entire view controller up, and the search bar with it.

Second step: handling the cancel button. The UISearchBar has a showsCancelButton, but if you try and animate that it comes off kinda clunky. The solution is to have the Cancel button on at all times – but set the search bar to be so wide that the cancel button is off the screen to the right. After this, a simple frame or constraint animation will get the job done.

self.searchWidth.constant = 320.f;
[self.searchBar setNeedsUpdateConstraints];
[UIView animateWithDuration:duration animations:^(){
[self.searchBar layoutIfNeeded];

Naturally you will want to combine this with the Navigation Bar example :/

Next, you will probably find that the status bar appears on top of the search bar. My solution to this was to create a spacer view to appear between the navigation bar and the search bar, and adjust the height via a constraint animation. The code for this is left as an exercise for the reader.

Have fun animating, and if you have any tips or tricks to share, let me know in the comments!


About Markk

Markk is an iOS developer.
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s