我以编程方式创建了标签栏控制器,其中包含一个具有RedViewController实例的viewcontroller数组
class TabBarViewController: UITabBarController, UITabBarControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
self.delegate = self
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let tab1 = Red()
let tab1BarItem = UITabBarItem(title: "Tab1", image:UIImage(named:"bell-off-7.png"), selectedImage:UIImage(named:"bell-7.png") )
tab1BarItem.tag = 0
tab1.tabBarItem = tab1BarItem
let tab2 = ObserverViewController()
let tab2BarItem = UITabBarItem(title: "Tab2", image: UIImage(named:"bell-off-7.png"), selectedImage: UIImage(named:"bell-7.png"))
tab2BarItem.tag = 1
tab2.tabBarItem = tab2BarItem
self.viewControllers = [tab1,tab2]
}
}
我如何使用类Red的实例来访问它的属性,因为Array viewController是UIViewController的返回类型
答案 0 :(得分:0)
从阵列中检索后,您只需将UIViewController
转换为Red
。
guard let redController = self.viewController.first as? Red else {return}
这样,redController
的类型为Red
。当在类型为超类的集合中存储某个类的子类时,类型信息永远不会丢失,因此您可以在将特定数组元素转换为它所来自的子类之后访问特定的子类属性。