iOS present和push
一、present和push
共同点:
present和push方法都可用于推出新的界面。 present和dismiss对应使用,push和pop对应使用。
不同点:
push:
由视图栈控制,每一个视图都入栈,调用之前的视图则需要出栈,可以返回上一级,也可以返回到根视图,其他视图,即可返回任意一层,一般用于同一业务不同界面之间的切换。
push是由UINavigationController
管理的视图控制器堆栈,在window下同时只能显示一个ViewController。
present:
弹出的视图是模态视图(我对模态视图的理解大概就是一个临时视图),只能逐级返回,一般用于不同业务界面的切换。
present是由UIViewController
管理的视图控制器堆栈,在window下可以以叠加的方式展示,当顶层的view透明时可以看到底层的view,但只有顶层的view可用户交互。
二、使用方法
1.push的使用
用UINavigationController的时候使用
跳转到指定页面:
[self.navigationController pushViewController:secondViewController animated:YES];
返回之前的视图:
- 返回上一级
[[self navigationController] popViewControllerAnimated:YES];
- 返回到根控制器
[self.navigationController popToRootViewControllerAnimated:YES];
- 返回到指定控制器
[self.navigationController popToViewController:FirstViewController animated:YES];
注意:push以后会在navigation的left bar自动添加back按钮,它的响应方法就是返回。所以一般不需要写返回方法,点back按钮即可。
2.present的使用
- 跳转到指定页面:
SecondViewController *viewController = [[SecondViewController alloc]init];
// 进行跳转
[self presentViewController:viewController animated:YES completion:nil];
}
- 返回上一页面:
[self dismissViewControllerAnimated:YES completion:nil];
改变present出来页面的样式:
viewController.modalPresentationStyle = [UIModalPresentationFullScreen];
三、页面的push/present的demo
1.第一个界面present第二个界面
//第一个界面的按下跳转 使用present
-(void)press{
SecondViewController *secondView = [[SecondViewController alloc]init];
UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:secondView];
navigation.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:navigation animated:YES completion:nil];
}
2.第二个界面push第三个界面
//第一个界面的按下跳转 使用present
-(void)press{
SecondViewController *secondView = [[SecondViewController alloc]init];
UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:secondView];
navigation.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:navigation animated:YES completion:nil];
}
3.第三个页面返回
//第三个界面的back 如果是dismiss那么就返回第一个界面 如果是pop那么就是第二个界面
- (void)back{
// [self dismissViewControllerAnimated:YES completion:nil];
[self.navigationController popViewControllerAnimated:YES];
}