如何将数据传递给UITabBarController?

时间:2017-05-25 12:39:00

标签: swift xcode swift3 uitabbarcontroller xcode8

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

以下不起作用:

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传递到UIViewControllers内的UITabBarController之一的正确方法是什么?

更新 这是我的主要故事板 StoryBoard

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

2 个答案:

答案 0 :(得分:1)

你太封闭了,只能让你只需要将segue.destination投射到UITabBarController时出现一个错误,你就可以了。

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

     postVC.hospitalName = "Khola Hospital"
}

答案 1 :(得分:0)

创建自定义UITabBarController课程并将数据传递到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"
}