如何有效获取当前加载的ViewController名称字符串?
解决获取当前ViewController类名的问题
嘿,我来帮你搞定这个需求!针对你提到的Storyboard场景、不想用字符串分割的要求,我整理了两个实用的方案:
方案1:封装UIViewController扩展(推荐)
虽然用到了字符串分割,但封装成扩展后调用超级简洁,而且这种操作的性能开销完全可以忽略,完全满足日常开发需求:
extension UIViewController { /// 获取不带模块前缀的纯类名字符串 var pureClassName: String { let fullClassName = String(describing: type(of: self)) return fullClassName.components(separatedBy: ".").last ?? fullClassName } }
调用示例(附通用的当前ViewController获取方法):
func getCurrentViewController() -> UIViewController? { guard let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else { return nil } var currentVC = window.rootViewController while let presentedVC = currentVC?.presentedViewController { currentVC = presentedVC } return currentVC } if let currentVC = getCurrentViewController() { print(currentVC.pureClassName) // 输出 "MyViewController1" }
方案2:借助Objective-C运行时(无需字符串分割)
如果确实不想用字符串分割,可以利用Objective-C的运行时特性,但需要给你的ViewController类添加@objc修饰来指定类名:
- 给目标ViewController类添加
@objc标记:
@objc(MyViewController1) class MyViewController1: UIViewController { // 你的业务代码 }
- 通过
classForCoder获取类名:
if let currentVC = getCurrentViewController() { let className = NSStringFromClass(currentVC.classForCoder) print(className) // 输出 "MyViewController1" }
这个方法不需要字符串分割,但缺点是需要给每个需要获取类名的ViewController手动添加@objc修饰,适合类数量较少的项目。
为什么你提到的其他方法不适用?
vc.title:这是页面的显示标题,和ViewController的类名没有必然关联,完全不是你需要的内容vc.nibName:Storyboard中的ViewController并非从单独的nib文件加载,所以这个属性会返回nil,确实无法生效
内容的提问来源于stack exchange,提问作者Jonas0000
相关产品推荐
相关产品推荐

