Install UITabBarController Controllers in Swift

I am trying to programmatically install the 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 the line

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

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

and with the line

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

I get an error message:

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

My problem is with AnyObject and typecasting, I think.

+3
source share
1 answer

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:

  • Do not make them optional. This requires that you initialize them with something when you activate your TabBarViewController . Perhaps the safest option.

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

     self.viewControllers = [cameraViewController!, profileViewController!] 
  • Make sure that cameraViewController and profileViewController not zero in viewDidLoad . It smells of poor design for me, though.

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

So, it comes down to how you initialize cameraViewController and profileViewController . Are they displayed before the view controllers of the tab bar are displayed? If so, I recommend adding custom init to my class.

+2
source

Source: https://habr.com/ru/post/1246067/


All Articles