[英]Transfer data from tab bar controller to ViewController
I have a typical ViewController:我有一个典型的 ViewController:
class ViewController: UIViewController{
override func viewDidLoad() {}
}
And I also have TabBarController which displays me the number of the current scene:而且我还有 TabBarController 显示当前场景的编号:
class TabBarController: UITabBarController {
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem!) {
if item == (self.tabBar.items as! [UITabBarItem])[0]{
print(1)
}
else if item == (self.tabBar.items as! [UITabBarItem])[1]{
print(2)
}
}
}
I need my ViewController to know the number of its scene.我需要我的 ViewController 知道它的场景数量。 (1 or 2).
(1 或 2)。 How can I deliver him this number for use from TabBarController?
我怎样才能从 TabBarController 向他提供这个号码以供使用?
What you want to do is, add a property called number
, or whatever you like, to your ViewController
class.您想要做的是,将一个名为
number
的属性或任何您喜欢的属性添加到您的ViewController
class。
class ViewController: UIViewController {
var number: Int!
}
Then in tabBarController's viewDidLoad
, loop through the view controllers, check if they are of type ViewController
, and then set their number
property to the index of the tabBarController's view controllers:然后在 tabBarController 的
viewDidLoad
中,遍历视图控制器,检查它们是否属于ViewController
类型,然后将它们的number
属性设置为 tabBarController 的视图控制器的索引:
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
for (index,vc) in (viewControllers!.enumerated())! {
if let viewController = vc as? ViewController {
vc.number = index
}
}
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem!) {
if item == (self.tabBar.items as! [UITabBarItem])[0]{
print(1)
}
else if item == (self.tabBar.items as! [UITabBarItem])[1]{
print(2)
}
}
}
Unless, are you wanting to set the value whenever the tab is selected?除非,您想在选择选项卡时设置值吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.