How To: Animate Showing and Hiding a UINavigationBar with Tap Gesture

The navigation bar is an important component of your app’s user interface but, sometimes, it can really get in the way of your content. Maybe you’d like to show a web page or an image, but the navigation bar occupies precious screen real estate, which essentially becomes dead space while a user is engaged with your content.

This tutorial quickly teaches you how to animate showing and hiding the navigation bar with a tap gesture.

#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>;

#define kNavBarDefaultPosition CGPointMake(160,22)

@interface UIViewController () <UIGestureRecognizerDelegate>;

@end

@implementation UIViewController

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

    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer]
    alloc] initWithTarget:self action:@slector(animateNavigationBar)];
    recognizer.delegate = self;
    recognizer.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:recognizer];
}

- (void)animateNavigationBar
{
    CALayer = self.navigationController.navigationBar.layer;

    // If the navigation bar is shown, hide it.
    // Else, if the navigation bar is hidden, show it.

    if (layer.position.x == kNavBarDefaultPosition.x &amp;&amp;
    layer.position.y == kNavBarDefaultPosition.y) {
         [UIView animateWithDuration:0.25 animations:^{
             layer.position = CGPointMake(layer.position.x,
             -self.navigationController.navigationBar.frame.
             size.height);
         }];
    } else {
        [UIView animateWithDuration:0.25 animations:^{
            layer.position = kNavBarDefaultPosition;
        }];
    }
}
Advertisements

6 thoughts on “How To: Animate Showing and Hiding a UINavigationBar with Tap Gesture

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s