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

下面我给一个演示的实例

相关推荐
微祎_1 小时前
构建一个 Flutter 点击速度测试器:深入解析实时交互、性能度量与响应式 UI 设计
flutter·ui·交互
2501_915106321 小时前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 小时前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
AAA阿giao2 小时前
从零拆解一个 React + TypeScript 的 TodoList:模块化、数据流与工程实践
前端·react.js·ui·typescript·前端框架
熊猫钓鱼>_>2 小时前
移动端开发技术选型报告:三足鼎立时代的开发者指南(2026年2月)
android·人工智能·ios·app·鸿蒙·cpu·移动端
晚霞的不甘2 小时前
Flutter for OpenHarmony 构建简洁高效的待办事项应用 实战解析
flutter·ui·前端框架·交互·鸿蒙
百思可瑞教育2 小时前
构建自己的Vue UI组件库:从设计到发布
前端·javascript·vue.js·ui·百思可瑞教育·北京百思教育
XPii14 小时前
Photoshop应用——将图片变为水墨画效果
ui·photoshop
AC梦17 小时前
unity中如何将UI上的字高清显示
ui·unity
LeoZY_20 小时前
开源项目精选:Dear ImGui —— 轻量高效的 C++ 即时模式 GUI 框架
开发语言·c++·ui·开源·开源软件