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
- Access the parent TabBarController: From
ViewController B, you can directly reference the tab bar controller that contains it. - Target the first tab's navigation controller: The first item in the tab bar's
viewControllersarray corresponds to your initial tab (index 0). Cast it toUINavigationControllerto access its navigation stack. - Fetch the top view controller: The last element in the navigation controller's
viewControllersarray is the currently pushed view controller (which isViewController A). - Get the class name: Use
String(describing: type(of: vc))to retrieve the class name ofViewController 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 likeViewController 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 forViewController Abeforehand.
内容的提问来源于stack exchange,提问作者VitDuck
相关产品推荐
相关产品推荐

