[英]How to pass data from ViewController to a ViewController in a tab bar iOS?
I'm trying to pass data from my main ViewController to another ViewController in a Tab Bar. 我试图将数据从主ViewController传递到选项卡栏中的另一个ViewController。
I have tried using the following code , and got an error Could not cast value of type 'Test.FirstViewController'
to 'Test.ViewController'
我尝试使用以下代码,但收到错误消息
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)
}
I just used the following code which just worked fine for me on Xcode 9 with swift 4.0. 我只是使用了下面的代码,该代码在swift 4.0的Xcode 9上运行良好。 The following method is declared in the View Controller class which just presents the First View Controller.
在仅显示第一个View Controller的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!
})
}
}
You can access the tab bar controllers in your ViewController
prepare
method and set your values. 您可以在
ViewController
prepare
方法中访问选项卡栏控制器并设置值。
Prepare for 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"
}
Then in your tab bar ViewControllers declare variables, you want to set the values to. 然后,在标签栏中,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 FirstViewController
SecondViewController SecondViewController
You could do a number of things, what I would do is to just make a global variable so that both view controllers can access it. 您可以做很多事情,我要做的只是创建一个全局变量,以便两个视图控制器都可以访问它。 Another option is to give each view controller a separate global variable, and when the view is loaded, the variable is set to self, then make a variable that can be set by the other view controller.
另一个选择是给每个视图控制器一个单独的全局变量,然后在加载视图时,将该变量设置为self,然后创建一个可以由另一个视图控制器设置的变量。
example: 例:
var data:Any?
viewDidLoad() {
viewControllerA = self
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.