[iOS] push 和 present Controller 的区别

目录

前言

[1.push & pop 方法](#1.push & pop 方法)

[push 方法](#push 方法)

[pop 方法](#pop 方法)

[2.present & dismiss 方法](#2.present & dismiss 方法)

[present 方法](#present 方法)

[dismiss 方法](#dismiss 方法)

[present 和 dismiss 的多级方法](#present 和 dismiss 的多级方法)


前言

push 和 present 分别是 ios 中的两种推出方法。下面我会结合实例来去介绍一下这两个方法。

1.push & pop 方法

push 方法

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

pop 方法

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

//返回指定的
NSArray *viewControllers = self.navigationController.viewControllers;
UIViewController *targetVC = viewControllers[0]; // 第一个控制器
[self.navigationController popToViewController:targetVC animated:YES];

//返回指定的
[self.navigationController popToRootViewControllerAnimated:YES];

2.present & dismiss 方法

present 方法

objectivec 复制代码
ViewControllerB* vcB = [[ViewControllerB alloc] init];
    UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:vcB];
    [self presentViewController:nav animated:YES completion:nil];

dismiss 方法

dissmiss 这里比较复杂一点他不能直接向 pop 一样返回指定的层数和根视图

这里会去介绍一个多级视图的方法

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

present 和 dismiss 的多级方法

在 iOS 中,每个控制器都有两个属性:

presentedViewController

• 含义:当前控制器 展示的(被我 present 出去的)控制器。

• 如果我没有弹出任何控制器,这个属性就是 nil。

presentingViewController

• 含义:展示我的 控制器。

• 如果我是被别人 present 出来的,这个属性就是我的"上一级";否则就是 nil。

这里引用一张图

那这里我们再结合 dissmiss

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

这个就可以实现从 c 到 a,越过两级视图。

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

这段代码就能实现追溯到根视图。

这一切的一切都和 presenting 和 presented 这两个方法有关。

下面我给一个演示的实例

相关推荐
2501_916007475 小时前
申请 iOS 推送证书并配置 APNs 群发推送教程
android·ios·小程序·https·uni-app·iphone·webview
电子云与长程纠缠6 小时前
UE5 Lyra PocketWorld进行3D内容UI预览 - 下
开发语言·学习·游戏·ui·ue5
weixin_403810136 小时前
iOS自动化脚本怎么避免风控?无屏幕镜像截图原理详解
ios·自动化·跨境电商·苹果群控·苹果投屏·多媒体运营
wangruofeng6 小时前
3 步把 MacBook 变成 7×24 远程主机,人在外面随时接管桌面
ios·agent·mac
weixin_403810136 小时前
iOS免越狱自动化蓝牙HID方案:不装代理也能跑脚本
运维·ios·自动化·跨境电商·ai智能体·ios投屏·苹果投屏
GitLqr18 小时前
Flutter 3.47 与 Dart 3.13:你必须了解的迁移指南
flutter·ios·dart
冯汉栩1 天前
Swift Control View,Label渐变颜色(源码)
开发语言·ios·swift
jike_20261 天前
iPhone日历查看会议纪要APP推荐:按日期查找历史录音更方便
ios·语音识别·iphone
冯汉栩1 天前
OC 技术 App上存蒲公英教程
ios
阿部多瑞 ABU1 天前
告别手工核图:基于 .NET + MuPDFCore 的 CAD 等轴测 PDF 材料表提取与新旧版本对比实战
后端·算法·ui·pdf·c#