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

TabBar切换至Item[3]时,如何获取ViewController A的名称?

How to Get the Name of ViewController A When Switched to Another Tab

Great question! Let's break this down based on how iOS tab bar and navigation controllers behave. When you switch tabs in a UITabBarController, the view controllers for inactive tabs don't get destroyed—they just stop being displayed. Since you pushed ViewController A onto the first tab's navigation stack, that stack remains intact even when you switch to the 4th tab.

Here's a straightforward way to retrieve ViewController A's name from ViewController B:

Step-by-Step Approach

  1. Access the parent TabBarController: From ViewController B, you can directly reference the tab bar controller that contains it.
  2. Target the first tab's navigation controller: The first item in the tab bar's viewControllers array corresponds to your initial tab (index 0). Cast it to UINavigationController to access its navigation stack.
  3. Fetch the top view controller: The last element in the navigation controller's viewControllers array is the currently pushed view controller (which is ViewController A).
  4. Get the class name: Use String(describing: type(of: vc)) to retrieve the class name of ViewController A.

Code Example (Swift)

// Inside ViewController B
func fetchViewControllerAName() -> String? {
    // Ensure we can access the tab bar controller
    guard let tabBarController = self.tabBarController else {
        return nil
    }
    
    // Retrieve the navigation controller for the first tab (index 0)
    guard let navController = tabBarController.viewControllers?[0] as? UINavigationController else {
        return nil
    }
    
    // Get the top view controller in the navigation stack (ViewController A)
    guard let viewControllerA = navController.viewControllers.last else {
        return nil
    }
    
    // Return the class name of ViewController A
    return String(describing: type(of: viewControllerA))
}

// To use the function
if let vcAName = fetchViewControllerAName() {
    print("ViewController A's name: \(vcAName)")
}

Quick Notes

  • Make sure the first tab's root controller is a UINavigationController (this is mandatory for pushing view controllers like ViewController A).
  • If you need the display title (not the class name), replace the final return line with return viewControllerA.title—just ensure you've set a title for ViewController A beforehand.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 07:03:43