-->

Hide Navigation Bar but not the back button

2020-06-29 06:23发布

问题:

i hide my navigation using:

[self.navigationController setNavigationBarHidden:YES animated:YES];

But i need to not hide the back button, it's Possible?

回答1:

nevan king is right but you can simply change the background image of the navigation bar or set it to nil. If you set it to nil or provide a transparent BG-image you would achieve the effect you need.

For iOS >= 5.0 you could simply set the appearance:

if([navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) // needed if iOS older than 5.0 is also supported
    [navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];

You can do that where ever you have a pointer to your navigation bar. E.g. inside of the viewDidLoad method of your ViewController.

For older iOS version you need a workaround by making a category of UINavigationBar and overwrite the drawRect method:

@implementation UINavigationBar (BackgroundImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed: @""];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

Both methods are compatible if you want to support all iOS versions.
Thus you should keep in mind, that the back button uses the same background image. So you will need to make a custom one.

UIImage *bgImageNormal = [UIImage imageNamed:@"backButtonImage.png"];

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage: bgImageNormal forState:UIControlStateNormal];

button.frame= CGRectMake(0.0, 0.0, bgImageNormal.size.width, bgImageNormal.size.height);
[button addTarget:self action:@selector(navigationBarBackButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside]; // your action method here

UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.leftBarButtonItem = closeButton;
[closeButton release];

This code needs to be implemented for each ViewController you are pushing to your navigation bar. A good place for it is also inside the viewDidLoad method.



回答2:

The back button is created by the navigation bar and always part of it, so it's not possible. You could hide and re-show the navigation bar when your user touches on the screen (this is what the Photos app does when you look at a single photo) or create a button and have it permanently on the top left of the screen. You could also make the navigation bar partly transparent so that the content underneath shows up.