[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 这两个方法有关。

下面我给一个演示的实例

相关推荐
插件开发2 小时前
Illustrator 插件开发:链接文件存在检查的原理与实战
ui·illustrator
xy34532 小时前
axure9.0 如何打造一个计时器(简单版)
前端·ui·html·axure·原型·产品设计
用户2181697049305 小时前
iOS 底层原理 Category load initialize 关联对象
objective-c
图扑软件12 小时前
下篇・换墨|主题/多语言/移动端,一套组件全覆盖
前端·javascript·ui·性能优化·数据可视化
getapi14 小时前
1 在 macOS 电脑上更新 Flutter iOS 应用到 App Store
flutter·macos·ios
可乐鸡翅yeah_14 小时前
App WebView 加载 M3U8 流媒体踩坑,安卓 iOS 混合开发播放异常定位
android·ios·harmonyos·m3u8·m3u8在线播放
代码的小搬运工1 天前
KVO学习
学习·ios·cocoa
方白羽1 天前
为什么 Android 非要用 Intent 传值?
android·ios·harmonyos
dora1 天前
iOS开发新手的第一行代码
ios
用户38034165882972 天前
视频编辑器的滤镜图内核:Node/Pin 模型怎么设计,撤销重做怎么才不崩
ios