如何将数据传递给 UITabBarController?

How to pass data to UITabBarController?

如何将数据从 UIViewController 传递到 UITabBarController 中的 UIViewController 之一?

以下无效:

let hospitalsController = segue.destination as! postRequest
hospitalsController.hospitalName = "Hospital Name"

尝试上面的代码时,出现以下错误:

Could not cast value of type 'UITabBarController' (0x10d05f418) to 'ProjectName.postRequest' (0x10b17fdd0).

当我尝试以下操作时:

let test = self.tabBarController?.viewControllers![0] as! UINavigationController
            let test2 = test.topViewController as! postRequest
            test2.hospitalName = "Khola Hospital"

应用程序崩溃且没有错误,

当我尝试打印 print(tabBarController?.viewControllers) 时,它在控制台中显示 nil

将数据从 UIViewController 传递到 UITabBarController 中的 UIViewControllers 之一的正确方法是什么?

更新 这是我的主要故事板

数据将从顶部UIViewController传递到右下UIViewController

你太封闭了,只需要一个错误就可以让它工作,你需要将 segue.destination 转换为 UITabBarController,然后你就可以开始了。

if let tabbarController = segue.destination as? UITabBarController, 
   let postVC = tabbarController.viewControllers?.first as? postRequest, 

     postVC.hospitalName = "Khola Hospital"
}

创建您的自定义 UITabBarController class 并将数据传递给那个 tabBarController 然后在您想要的 ViewController 中您想要获得医院名称的地方只需检查可用性tabBarController 并获取医院名称

class YourCustomTabBarController: UITabBarController {
    var hospitalName = ""
    //Do You Other Work Below
}

class PostRequest: UIViewController {
    var hospitalName = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        if let tabBarVC = self.tabBarController as? YourCustomTabBarController {
            self.hospitalName = tabBarVC.hospitalName
        }
        //Handle Other Work.
    }
}


if let tabBarVC = segue.destination as? YourCustomTabBarController {
    tabBarVC.hospitalName = "XYZ Hospital"
}