在Swift中设置UITabBarController的视图控制器
我想以编程方式设置我的自定义TabBarController的视图控制器:
import UIKit class TabBarViewController: UITabBarController, UITabBarControllerDelegate { var cameraViewController: UIViewController? var profileViewController: UIViewController? override func viewDidLoad() { super.viewDidLoad() self.delegate = self //self.viewControllers = [cameraViewController, profileViewController] as! [AnyObject]? let controllers: [UIViewController?] = [cameraViewController, profileViewController] self.setViewControllers(controllers as! [AnyObject], animated: true) }
但是与线
self.viewControllers = [cameraViewController, profileViewController] as! [AnyObject]?
我得到一个错误,我不能将[UIViewController]转换为[AnyObject?]
和线
self.setViewControllers(controllers as! [AnyObject], animated: true)
我得到一个错误说:
Cannot invoke 'setViewControllers' with an argument list of type '([AnyObject], animated: Bool)'
我的问题是AnyObject和types转换我猜。
问题是你试图使用的视图控制器被声明为可选的:
var cameraViewController: UIViewController? var profileViewController: UIViewController?
所以你有三个select:
-
不要让它们可选。 这就要求你在启动
TabBarViewController
时候用一些东西来初始化它们。 也许最安全的select。 -
如果您知道
cameraViewController
和profileViewController
在viewDidLoad
中永远不会nil
:self.viewControllers = [cameraViewController!, profileViewController!]
-
检查
cameraViewController
和profileViewController
在viewDidLoad
是否不为零。 这味道虽然对我来说很糟糕。if let c = cameraViewController, let p = profileViewController { self.viewControllers = [c, p] }
所以它归结为如何初始化cameraViewController
和profileViewController
。 它们是在标签栏视图控制器显示之前设置的吗? 如果是这样,我build议添加一个自定义的init
到你的类。