Set view controllers of UITabBarController in Swift

最后都变了- 提交于 2019-12-19 04:04:46

问题


I am trying to programatically set view controllers of my custom 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)

}

But with line

self.viewControllers = [cameraViewController, profileViewController] as! [AnyObject]?

I get an error that I cannot convert [UIViewController] to [AnyObject?]

and with line

self.setViewControllers(controllers as! [AnyObject], animated: true)

I get an error saying:

Cannot invoke 'setViewControllers' with an argument list of type '([AnyObject], animated: Bool)'

My problem is with AnyObject and typecasting I guess.


回答1:


The problem is that the view controllers you are trying to use are declared optional:

var cameraViewController: UIViewController?
var profileViewController: UIViewController?

So you have three options:

  • Don't make them optional. This requires that you initialize them with something when you initalize your TabBarViewController. Maybe the safest option.

  • If you know that cameraViewController and profileViewController are never nil in viewDidLoad:

    self.viewControllers = [cameraViewController!, profileViewController!]
    
  • Check if cameraViewController and profileViewController are not nil in viewDidLoad. This smells like bad design to me though.

    if let c = cameraViewController, let p = profileViewController {
        self.viewControllers = [c, p]
    }
    

So it boils down to how you initialize cameraViewController and profileViewController. Are they set before the tab bar view controllers is shown? If so, I recommend adding a custom init to your class.



来源:https://stackoverflow.com/questions/31720420/set-view-controllers-of-uitabbarcontroller-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!