【iOS】push与present Controller的区别

文章目录


前言

iOS推出与退出界面有两种方式------push与present,接下来笔者分别介绍这两种方式


一、push方法

objectivec 复制代码
    SecondViewController *second = [[SecondViewController alloc] init];
    [self.navigationController pushViewController:second animated:YES];

二、pop方法

objectivec 复制代码
	//返回上一级
	[self.navigationController popViewControllerAnimated:YES];

	//返回根视图
	[self.navigationController popToRootViewControllerAnimated:YES];

	//返回指定级数 (objectAtIndex:参数为想要返回的级数)
	[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0]  animated:YES];

三、present方法

objectivec 复制代码
    SecondViewController *second = [[SecondViewController alloc] init];
    [self presentViewController:second animated:YES completion:nil];

四、dismiss方法

objectivec 复制代码
    [self dismissViewControllerAnimated:YES completion:nil];

五、dismiss多级的方法

presentedViewController和presentingViewController是UIViewController里面的两个属性
PresentedViewController 与 PresentingViewController区别
presentedViewController:The view controller that was presented by this

view controller or its nearest ancestor. 由这个视图控制器或它最近的祖先呈现的视图控制器

presentingViewController:The view controller that presented this view

controller (or its farthest ancestor.) 呈现此视图控制器(或其最远祖先)的视图控制器。
假设从A控制器通过present的方式跳转到了B控制器,那么 A.presentedViewController 就是B控制器;

B.presentingViewController 就是A控制器;


举例

创建四个页面ABCD,例如我们想从D->A,我们可以用如下方法:

objectivec 复制代码
    UIViewController *rootVC = self.presentingViewController;
     while  (rootVC. presentingViewController ) {
              rootVC = rootVC.presentingViewController ;
             }
    [rootVC dismissViewControllerAnimated:YES completion:nil];

例如我们想从D->B,我们可以使用presenting来跳转页面

objectivec 复制代码
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];

如下代码也可以实现D->B

objectivec 复制代码
    UIViewController *rootVC =  self.presentingViewController;
    while (![rootVC isKindOfClass:[SecondViewController class]])  {
        rootVC = rootVC.presentingViewController;
    }
    [rootVC dismissViewControllerAnimated:YES completion:nil];

动画

相关推荐
健了个平_243 小时前
iOS 27 适配笔记
ios·xcode·wwdc
Tr2e4 小时前
🐱 从 0 到 1:用 Swift 手搓一个 macOS 桌面宠物(附源码)
macos·ios·swift
iOS开发上架哦6 小时前
Jenkins 自动上传 IPA 到 App Store 把发布步骤融入 CI/CD
后端·ios
Mac技巧大咖7 小时前
macOS 27 或成 Intel Mac 分水岭:老款 Mac 用户升级前要注意什么?
macos·macos 27
ZJPRENO7 小时前
2026 苹果 WWDC 完整总结
ios
上天_去_做颗惺星 EVE_BLUE9 小时前
【新 Linux 服务器上手全攻略】系统巡检、存储规划与开发环境初始化
linux·运维·服务器·ubuntu·macos·centos
REDcker9 小时前
WWDC2026系统更新综述
macos·ios·开发者·apple·wwdc·ipados·wwdc2026
星星电灯猴10 小时前
全面解决Charles抓取HTTPS请求响应中文乱码问题的方法与技巧
后端·ios
人月神话-Lee10 小时前
【WWDC】Core AI:iOS 端侧大模型新纪元
人工智能·ios·ai·swift·wwdc·core ai
Sammyyyyy10 小时前
2026 Mac 本地大模型部署深度解析与混合架构指南
数据库·人工智能·macos·ai·架构·servbay