You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在UIKit导航控制器中不依赖字符串匹配从SwiftUI视图获取UIViewController

解决方案:基于类型匹配优化popTo函数

直接利用Swift的类型检查能力,替换原有的字符串匹配逻辑,就能让函数更健壮。修改后的代码如下:

func popTo<T: View>(viewType: T.Type, animated: Bool) {
    // 通过类型判断筛选对应UIHostingController
    if let targetController = rootNavigationController.viewControllers.first(where: {
        $0 is UIHostingController<T>
    }) {
        rootNavigationController.popToViewController(targetController, animated: animated)
    }
}

核心说明

  • 原逻辑依赖description字符串匹配,容易因为系统版本更新、视图描述格式变化失效;改用$0 is UIHostingController<T>后,直接通过编译期类型验证筛选目标控制器,稳定性大幅提升
  • UIHostingController<T>明确指向包裹了指定SwiftUI View(T类型)的宿主控制器,完全贴合你的需求场景

使用示例

比如要跳转到MyView对应的页面,直接调用:

popTo(viewType: MyView.self, animated: true)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:04:53