UI基础之UINavigationController

导航控制器默认自带一个根控制器

AppDelegate.m文件中 初始化创建一个根控制器,且将此导航控制器设置为系统根控制器

FirstViewController * first=[[FirstViewController alloc] init];

UINavigationController  * nv=[[UINavigationController alloc] initWithRootViewController:first];

self.window.rootViewController=nv;

 

导航控制器的存储方式是堆栈的方式,先进后出

 

1 把页面加入到堆栈中是用push方法,压入

    SecondViewController * second=[[SecondViewController alloc] init];

    [self.navigationController pushViewController:second animated:YES];

 

2 把页面跳转到前面的页面用pop方法,推出

 

>1 跳转到上一页

//推出本页面控制器

[self.navigationController popViewControllerAnimated:YES];

 

>2 跳转到根视图中 

[self.navigationController popToRootViewControllerAnimated:YES];

 

>3 跳转到之前非前页的任意页面

首先要找到存在堆栈中(数组中)的那页控制器

//必须先找到堆栈中的第二页的控制器

    UIViewController *second=self.navigationController.viewControllers[1];//面向对象的多态的概念,用父控制器来写

    [self.navigationController popToViewController:second animated:YES];

 

全局就一个导航栏

AppDelegate.m文件中写

 

    nv.navigationBar.hidden=NO;

 

//    nv.navigationBar.barTintColor=[UIColor redColor];

 

//    nv.navigationBar.backgroundColor=[UIColor redColor];半透明的效果

 

    nv.navigationBar.barTintColor=[UIColor colorWithRed:79/255.0 green:208/255.0 blue:201/255.0 alpha:1];

这样每个都加上了导航页

 

若想在导航页上加东西,则是在每个小控制器里面加

    /********增加导航按钮*********/

  //添加系统自带的item

    UIBarButtonItem *left1=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(click)];

    

    //添加自定义的图片

    UIBarButtonItem * left2=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"comment_icon_hot"] style:

                             UIBarButtonItemStylePlain target:self action:@selector(click)];

    self.navigationItem.leftBarButtonItems=@[left1,left2];

    

 

    //添加文字选项

    UIBarButtonItem * right1=[[UIBarButtonItem alloc] initWithTitle:@"haha" style:UIBarButtonItemStylePlain target:self action:@selector(click)];

    //自定义item

    UIView * view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];

    view.backgroundColor=[UIColor blackColor];

    UIBarButtonItem * right2=[[UIBarButtonItem alloc] initWithCustomView:view];

    

    self.navigationItem.rightBarButtonItems=@[right1,right2];

    

    //自定义中间item内容 中间item是个view

    UIView * titleView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 35)];

    UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)

                    ];

    [label setText:@"我的"];

    label.center=titleView.center;

    label.textAlignment=NSTextAlignmentCenter;

    [titleView addSubview:label];

    titleView.backgroundColor=[UIColor whiteColor];

    self.navigationItem.titleView=titleView;

 

原文地址:https://www.cnblogs.com/gzoof/p/5584014.html