如何将数据从ViewController传递到iOS标签栏中的ViewController?

时间:2017-11-05 01:01:05

标签: ios swift uiviewcontroller uitabbar

我试图将数据从我的主ViewController传递到标签栏中的另一个ViewController。

enter image description here

我尝试使用以下代码,但Could not cast value of type 'Test.FirstViewController'错误'Test.ViewController'

override func viewWillAppear(_ animated: Bool)
{
    super.viewWillAppear(animated)
    let tab1Controller = self.tabBarController?.viewControllers?.first as! ViewController
    print(tab1Controller.test)
}

3 个答案:

答案 0 :(得分:2)

我刚刚使用了以下代码,它在Xcode 9上使用swift 4.0正常工作。在View Controller类中声明了以下方法,该类只显示了First View Controller。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "sendingToTabBar" {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tabVC = storyboard.instantiateViewController(withIdentifier: "tabVC") as! UITabBarController
        self.present(tabVC, animated: true, completion: {
            let vc = tabVC.selectedViewController as! FirstViewController
            vc.dataLBL.text = self.dataTF.text!
        })
    }
}

答案 1 :(得分:1)

您可以使用ViewController prepare方法访问标签栏控制器并设置值。

准备segue

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let barViewControllers = segue.destination as! UITabBarController
    let destinationViewController = barViewControllers.viewControllers?[0] as! FirstViewController
    destinationViewController.test = "Hello TabBar 1"

    // access the second tab bar
    let secondDes = barViewControllers.viewControllers?[1] as! SecondViewController
    secondDes.test = "Hello TabBar 2"
}

然后在标签栏中ViewControllers声明变量,您要将值设置为。

@IBOutlet weak var label: UILabel!
var test: String?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    label.text = test
}

<强> FirstViewController

enter image description here

<强> SecondViewController

enter image description here

答案 2 :(得分:-1)

你可以做很多事情,我要做的就是创建一个全局变量,以便两个视图控制器都可以访问它。另一种选择是为每个视图控制器提供一个单独的全局变量,当加载视图时,变量设置为self,然后创建一个可由另一个视图控制器设置的变量。

示例:

var data:Any?
viewDidLoad() {
    viewControllerA = self
}