导航条继承与UIView,且通常只是作为多个UINavigationItem的容器,而且他以Stack的形式来管理多个UINavigationItem的控件,这意味着导航条上每次只能看到一个UINavigationItem对象。
在同一时刻,只能看到最上面的UINavigationItem,UINavigationBar最底层的控件被称作root UINavigationItem;
方法:
-pushNavigationItem: animated:该方法将一个UINavigationItem压入UINavigationBar的栈中
- (void)setItems:(nullable NSArray<UINavigationItem *> *)items animated:(BOOL)animated;同事为导航条设置多个UINavigationItem控件
- (nullable UINavigationItem *)popNavigationItemAnimated:(BOOL)animated;
topItem: 用于返回UINavigationItem控件最顶层的UINavigationItem
backItem:用于返回UINavigationItem控件最顶层下面的UINavigationItem
UINavigationItem也作为一个容器,他的组成就不用说了,相信大家都知道,那我们看看不怎么了解的属性:
hidesBackButton:该属性用于设置或返回是否显示后退按钮。如果将该属性设置为YES,那么就会隐藏后退按钮。
下方通过代码了解UINavigationIBar
// #import "ViewController.h" @interface ViewController () { //记录当前是添加第几个UINavigationItem的计数器 NSInteger count; UINavigationBar *navigationBar; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. count = 1; //创建导航条 navigationBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 44)]; [self.view addSubview:navigationBar]; //调用push方法添加一个UINavigationItem [self push]; } -(void)push { //把导航栏集合添加到导航栏中,设置动画打开 [navigationBar pushNavigationItem:[self makeNavItem] animated:YES]; count ++; } -(void)pop { if (count > 2) { count--; //弹出最顶层的UINavigationItem [navigationBar popNavigationItemAnimated:YES]; }else{ UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"只剩下最后一个导航项,再出栈就没有了" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alert show]; } } -(UINavigationItem *)makeNavItem { //创建一个导航项 UINavigationItem *navigationItem = [[UINavigationItem alloc]init]; UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(push)]; UIBarButtonItem *rightButton =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(pop)]; navigationItem.title = [NSString stringWithFormat:@"第%d个导航项",count]; [navigationItem setLeftBarButtonItem:leftButton]; navigationItem.rightBarButtonItem = rightButton; return navigationItem; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end上方程序中,push,pop方法负责用于控制导航条中的 UINavigationItem的出栈进栈
效果图:
进出栈设置的动画,所以进出栈会有向左或者向右滑动的效果