如何隐藏NavigationController

如何隐藏NavigationController?

隐藏NavigationController只需要调用一个方法就可以了:

1
2
//OC
self.navigationController.navigationBar.hidden = YES;

要回复它只用把状态改为NO就好。

ScrollViewTableView向上滑动隐藏NavigationController

如果是在一个ScrollView或者是一个TableView里面,想要实现向上滑动隐藏NavigationController,调用这个函数即可:

1
2
3
4
5
6
7
8
9
10
11
12
//OC
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
if (velocity.y > 0.0)
{
//向上滑动隐藏导航栏
[self.navigationController setNavigationBarHidden:YES animated:YES];
}else
{
//向下滑动显示导航栏
[self.navigationController setNavigationBarHidden:NO animated:YES];
}
}

其中

1
2
//OC
[self.navigationController setNavigationBarHidden:YES animated:YES];

是带有动画效果的,如果不需要动画效果可以直接用

1
2
//OC
self.navigationController.navigationBar.hidden = YES;

不过应该不会有人不想用动画效果吧

效果图:

hide NavigationController


当然从效果图来看这样实现并不好,因为StatusBartableView的内容重合了,现在可以做一点优化。

viewDidLoad里面添加:

1
2
//OC
[self setNeedsStatusBarAppearanceUpdate];

添加一个函数:

1
2
3
4
5
6
//OC
- (UIStatusBarStyle)preferredStatusBarStyle
{

return UIStatusBarStyleLightContent;
}

效果图:

“Hide”status bar


那如果要”保留”StatusBar要怎么做呢?

网上查了一下,有一个思路是把NavigationController的高度降为22,这样看起来就像是保留了StatusBar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//OC

@property (assign, nonatomic)BOOL isHidden;
//…………

-(void)showNavigationController{
if (self.isHidden) {
CGRect frame = self.navigationController.navigationBar.frame;
frame.origin.y = 20;
[UIView animateWithDuration:0.2 animations:^{
self.navigationController.navigationBar.frame = frame;

[self.item setTitle:@"item"];
self.title = @"Title";
}];
self.isHidden= NO;
}
}

-(void)hideNavigationController{
if (!self.isHidden) {
CGRect frame = self.navigationController.navigationBar.frame;
frame.origin.y = -24;
[UIView animateWithDuration:0.2 animations:^{
self.navigationController.navigationBar.frame = frame;

// 隐藏navigationController上的控件
[self.item setTitle:@""];
self.title = @"";
} completion:nil];
self.isHidden=YES;
}
}

然后修改下scrollViewWillEndDragging就可以了

1
2
3
4
5
6
7
8
9
10
11
12
13
//OC
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
if (velocity.y > 0.0)
{
//向上滑动隐藏导航栏
[self hideNavigationController];

}else
{
//向下滑动显示导航栏
[self showNavigationController];
}
}

效果图:

代码下载 Xcode6.4

##iOS8之后

1
2
//objective-c
self.navigationController.hidesBarsOnSwipe = YES;
1
2
//swift
self.navigationController!.hidesBarsOnSwipe = true;