You need to enable JavaScript to run this app. iOS与iPadOS下类似show()的通用pop/dismiss ViewController方法问询
优惠活动
大模型
产品
解决方案
定价
更多

iOS与iPadOS下类似show()的通用pop/dismiss ViewController方法问询

问题答案

UIKit 原生没有提供和 show(_ vc: UIViewController, sender: Any?)、showDetailViewController(_ vc: UIViewController, sender: Any?) 对等的、自动适配容器类型的通用返回方法,但我们可以通过扩展 UIViewController 自己实现逻辑一致的通用返回能力。

实现思路

通用返回的判断逻辑和系统 show 系列方法的适配逻辑对齐,自动识别当前控制器的展示场景选择对应返回操作:

  • 若当前控制器嵌套在 UINavigationController 中,且导航栈内控制器数量大于1,执行 pop 操作
  • 若当前控制器是通过 present 方式弹出的,执行 dismiss 操作
  • 适配横竖屏切换下的 UISplitViewController 场景,支持分栏状态下的详情页返回

封装代码示例

extension UIViewController {
    /// 通用返回方法,自动适配pop/dismiss/分栏返回逻辑
    func universalGoBack(animated: Bool = true, completion: (() -> Void)? = nil) {
        // 优先处理导航栈pop场景
        if let navController = navigationController, navController.viewControllers.count > 1 {
            navController.popViewController(animated: animated)
            completion?()
            return
        }
        // 处理present弹窗dismiss场景
        if presentingViewController != nil {
            dismiss(animated: animated, completion: completion)
            return
        }
        // 处理UISplitViewController分栏详情页返回场景
        if let splitController = splitViewController, !splitController.isCollapsed {
            splitController.show(.primary)
            completion?()
        }
    }
}

使用方式

直接在需要执行返回操作的控制器中调用即可,无需关心当前控制器的父容器类型,和系统show系列方法的使用体验完全一致:

// 任意场景下调用即可自动执行对应返回操作
universalGoBack(animated: true)

内容的提问来源于stack exchange,提问作者udbhateja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 03:06:01