Set view controllers of UITabBarController in Swift

后端 未结 1 1211
故里飘歌
故里飘歌 2021-01-06 08:41

I am trying to programatically set view controllers of my custom TabBarController:

import UIKit

class TabBarViewController: UITabBarController, UITabBarCont         


        
1条回答
  •  鱼传尺愫
    2021-01-06 09:21

    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.

    0 讨论(0)
提交回复
热议问题