pushViewController 导航控制器入栈的方式切换页面
presentViewController 模态切换的方式切换页面
1> 用 UINavigationController 的时候用 pushViewController:animated
返回之前的视图 [[self navigationController] popViewControllerAnimated:YES];
push 以后会在 navigation的 left bar自动添加back按钮,它的响应方法就是返回,所以一般不需要写返回方法,点back按钮即可
大部分时候,系统自定义的backButton样式不能满足我们需求。
所以我们需要自定义leftBar的button
UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 30)];
[backButton setAttributedTitle:[[NSAttributedString alloc]initWithString:@""] forState:UIControlStateNormal];
[backButton setImage:[UIImage imageNamed:@"backImage"] forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
self.navigationItem.hidesBackButton = YES;
self.navigationItem.leftItemsSupplementBackButton = YES;
//可以设置hidden属性
//self.navigationItem.leftBarButtonItem.customView.hidden=YES;
2> 其他时候用presentModalViewController:animated
[self presentModalViewController:controller animated:YES];
返回之前的视图 [self dismissModalViewControllerAnimated:YES];
3> 切换视图一般用不到 addSubview
UINavigationController是导航控制器,如果pushViewController的话,会跳转到下一个ViewController,点返回会回到现在这个ViewController;
如果是addSubview的话,其实还是对当前的ViewController操作,只是在当前视图上面又“盖”住了一层视图,其实原来的画面在下面呢,看不到而已。(当然,也可以用insertSubView atIndex那个方法设置放置的层次)。
基本操作:
1.设置根视图
在AppDelegate.m文件中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
UINavigationController *nav = [UINavigationController new];
self.window.rootViewController = nav;
LZHMainViewController *mainView = [LZHMainViewController new];
[nav pushViewController:mainView animated:YES];
[self.window makeKeyAndVisible];
return YES;
}
设置好了根视图,我们也能用push方法跳转到别的控制器。
不过在主UI界面中有导航栏会影响美观,所以我们要隐藏导航栏。
2.隐藏导航栏
隐藏导航栏要实现UINavigationControllerDelegate与UIGestureRecognizerDelegate代理
self.navigationController.delegate = self;
self.navigationController.interactivePopGestureRecognizer.delegate = self;
代理方法
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animate{
if([viewController isKindOfClass:[self class]]){
[navigationController setNavigationBarHidden:YES animated:YES];
}
else{
[navigationController setNavigationBarHidden:NO animated:YES];
}
}
至此,我们已经可以实现没有导航栏进行push压栈了
ps:self.edgesForExtendedLayout = UIRectEdgeNone;
通过设置edgesForExtendedLayout属性,可以指定view是否可以延伸至整个屏幕。
默认值是UIRectEdgeAll,意味着view会被延伸至整个屏幕(view.height=设备屏幕高度)
UIRectEdgeNone——view.height=设备屏幕高度-导航栏高度
关于这个属性,值得一提的是:它只有当viewController被嵌到别的container view controller中时才会起作用