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

Swift中如何传入类型数组,判断对象是否继承其中类型并过滤顶层VC

改进topMostViewController方法以排除指定类型的视图控制器

你可以给原方法添加一个排除类型数组参数,通过类型检查跳过指定的视图控制器,具体实现如下:

extension UIViewController {
    func topMostViewController(excluding excludedTypes: [AnyClass] = []) -> UIViewController {
        // 先检查当前presented的控制器是否在排除列表里
        if let presented = self.presentedViewController {
            let shouldExclude = excludedTypes.contains { presented.isKind(of: $0) }
            if shouldExclude {
                return self
            }
            return presented.topMostViewController(excluding: excludedTypes)
        }
        
        // 处理导航控制器,传递排除类型参数
        if let navigation = self as? UINavigationController {
            return navigation.visibleViewController?.topMostViewController(excluding: excludedTypes) ?? navigation
        }
        
        // 处理标签控制器,传递排除类型参数
        if let tab = self as? UITabBarController {
            return tab.selectedViewController?.topMostViewController(excluding: excludedTypes) ?? tab
        }
        
        return self
    }
}

关键说明:

  • 参数excludedTypes默认值为空数组,不需要排除类型时可以直接调用topMostViewController(),和原方法用法一致
  • 用isKind(of:)判断presented控制器是否属于排除列表中的类型,符合条件就返回当前控制器,不再继续递归
  • 递归调用时要把排除类型数组传递下去,保证导航、标签控制器的子控制器检查也生效

调用示例:

比如要排除UIAlertController,直接传入对应的类型即可:

let topVC = UIApplication.shared.keyWindow?.rootViewController?.topMostViewController(excluding: [UIAlertController.self])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 09:12:35