我是一枚刚学习iOS的菜鸟,项目中经常会涉及到UIViewController之间的跳转,常用的就是PushViewController及PresentViewController,现在简单介绍下他们之间的区别。
PushViewController与PresentViewController的区别
PushViewController是导航的方式跳转,左右切换,与PopViewController对应,以栈的方式管理,可以把栈理解成一个瓶子,用户能看到的就是瓶子最上面的东西。而PreSentViewController是模态的方式跳转,上下切换,与dismissViewController对应。本质上是用一个模态ViewController遮住原来的ViewController,但是可以设置新模态窗口的尺寸,所以不一定会把旧的ViewController完全遮住(如果不设置,默认完全遮住)
假设有两个页面A、B,A为ViewController,B为SecondViewController,跳转的几种代码如下:
PushViewController方式
从A->B
SecondViewController *secondViewController = [[SecondViewController alloc] init];
[self.navigationController pushViewController:secondViewController animated:YES];
//[self.navigationController setNavigationBarHidden:YES animated:YES]; // 隐藏导航栏
从B->A
[self.navigationController popViewControllerAnimated:NO];
这里有个坑,在使用PushViewController跳转时发现没起作用。不要着急,这是因为self.navigationController为nil,我们只要添加根视图为NavigationController就行了。解决这个问题有两个方法:
1.storyboard的方式
在xcode->Editor->Embed In->Navigation Controller
2.代码的方法,修改AppDelegate.m文件
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
ViewController *viewController = [[ViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:viewController];
self.window.rootViewController = nav;
[self.window makeKeyAndVisible];
return YES;
}
PreSentViewController方式
从A->B
SecondViewController *secondViewController = [[SecondViewController alloc] init];
[self presentViewController:secondViewController animated:YES completion:^{
}];
从B->A
[self.navigationController dismissViewControllerAnimated:NO completion:^{
}];
简单的跳转这样已经可以实现了,但是我在网上看到另外一种跳转方式,原因说是为了解决从A跳转到B时导航栏消失的问题,但是我在项目中做悬浮框时也必须这样写,还不大理解,先贴出来
SecondViewController *secondViewController = [[SecondViewController alloc] init];
UINavigationController *navigationcontoller = [[UINavigationController alloc]initWithRootViewController:secondViewController];
navigationcontoller.navigationBar.hidden = YES;
[self presentViewController:navigationcontoller animated:YES completion:^{
}];