Edoardo
Edoardo

Reputation: 65

Hide/Unhide UINavigationbar when the screen is tapped

I'm very new with iOS Development and I have just created one of my first apps, in my .xib file I have a UINavigationBar that I want to hide/show when a part of the screen is tapped by the user (like in the Photo app). I've found some snippets online but I don't know where and how to use those.

I'd appreciate a lot if somebody could give me detailed informations about how to do this.

Upvotes: 4

Views: 10637

Answers (2)

Jano
Jano

Reputation: 63667

Add this toggle method anywhere in your UIViewController. This hides on first tap and shows again in second tap.

- (void)toggleNavBar:(UITapGestureRecognizer *)gesture {
    BOOL barsHidden = self.navigationController.navigationBar.hidden;
    [self.navigationController setNavigationBarHidden:!barsHidden animated:YES];
}

If there is no navigation controller, link the navigation bar with an IBOutlet and replace with

- (void)toggleNavBar:(UITapGestureRecognizer *)gesture {
    BOOL barsHidden = self.navBar.hidden;
    self.navBar.hidden = !barsHidden;
}

Then add the following in the method -(void)viewDidLoad {}

UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleNavBar:)];
[self.view addGestureRecognizer:gesture];
[gesture release];

If the view where you are going to tap is a UIWebViewController, you have to add the protocol to the view controller and set it as delegate gesture.delegate = self; then add the following:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

This is needed because the UIWebViewController already implements its own gesture recognizers.

Upvotes: 21

jemmons
jemmons

Reputation: 18657

Ultimately, you want to send the -setHidden: message to your navigation bar. The easiest way to do this is to make an Outlet and an Action in your in your view controller. Then, in your .xib file, connect the navigation bar to the outlet and some button (even a large, full screen one) to the action.

Outlets and Actions are basic techniques used over and over in iOS (and Mac) programming, so if you don't understand them, best go read up on them now. Every beginning iOS/Mac programming book covers this topic as does Apple's own Getting Started guide (pay particular attention to the Configuring the View section).

Inside your action, send a message to the outlet like so:

-(void)myButtonAction:(id)sender{
  [[self myNavigationBarOutlet] setHidden:YES];
}

This will hide the navigation bar whenever your button is tapped.

(This assumes you have a UINavigationBar in your .xib like you say. These directions will be different if you're working with a UINavigationController that manages its own UINavigationBar)

Upvotes: 0

Related Questions