上篇中,我们提到的自定义的tabbar
,随之而来的就是自定义导航控制器UINavigationController
.
- 一般在开发APP中,我们是把
UITabBarController
和UINavigationController
结合起来用的.上一篇中我们提到如何自定义tabbar
用KVC来自定义Tabbar,这篇我们来简单谈谈如果自定义导航控制器.方法也很简单,我们直接上代码.
1.如果想让UIViewController
拥有push
和pop
的能力,那么就必须给这个控制器的根视图设置为导航控制器
UIViewController *vc = [[UIViewController alloc]init];
UINavigationController *navVC = [[UINavigationController alloc]initWithRootViewController:vc];
这样的话,这个控制器就有了导航控制器的能力了.
2.结合UITabBarController
来设置.(这段代码是给tabbar设置子控制器的代码,如果不明白请看用KVC来自定义Tabbar)
-(void)setupChildVc:(UIViewController *)vc title:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage{
//设置文字和图片
vc.tabBarItem.title = title;
vc.tabBarItem.image = [UIImage imageNamed:image];
vc.tabBarItem.selectedImage = [UIImage imageNamed:selectedImage];
vc.view.backgroundColor = [UIColor colorWithRed:arc4random_uniform(100)/100.0 green:arc4random_uniform(100)/100.0 blue:arc4random_uniform(100)/100.0 alpha:1.0];
//设置为导航控制器,但是这里的是系统的
UINavigationController *navVc = [[UINavigationController alloc]initWithRootViewController:vc];
[self addChildViewController:navVc];
}
3.如果我们要用自己的,就要创建一个继承于UINavigationController
的控制器,下面我们简称XTNavigationController
,在XTNavigationController.m
中我来拦截页面的push
.
-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
if (self.childViewControllers.count > 0) {
//这里是设置了一个返回按钮,效果图如下
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"返回" forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"navigationButtonReturn"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"navigationButtonReturnClick"] forState:UIControlStateHighlighted];
button.size = CGSizeMake(70, 30);
//让按钮内部的所有内容左对齐
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//让按钮的内容往左偏移10
button.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
// 修改导航栏左边的item
viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
// 隐藏tabbar
viewController.hidesBottomBarWhenPushed = YES;
}
//这句super的push要放在后面, 让viewController可以覆盖上面设置的leftBarButtonItem
[super pushViewController:viewController animated:animated];
}
-(void)back{
[self popViewControllerAnimated:YES];
}
4.这样的话侧滑返回的手势就没了,咱们还需要开启
-(void)viewDidLoad {
[super viewDidLoad];
//设置导航条的图片
[self.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbarBackgroundWhite"] forBarMetrics:UIBarMetricsDefault];
// 如果滑动移除控制器的功能失效,清空代理(让导航控制器重新设置这个功能)
self.interactivePopGestureRecognizer.delegate = nil;
}
- 这样的话,无论我们在哪里点击
push
进去的页面,tabbar
都是隐藏的,这样就对我们开发过程中是及其重要省力的,欢迎大家尝试!!! -
这个就是我们来自定义这个导航条,还是用的原生的来做.
-
如有错误,欢迎雅正