在Swift中设置UITabBarController的视图控制器

4

我正试图以编程方式设置自定义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)

}

但是使用 line 进行

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 和类型转换有关。
1个回答

4
问题在于你尝试使用的视图控制器被声明为可选项:
var cameraViewController: UIViewController?
var profileViewController: UIViewController?

所以你有三个选择:

  • 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]
    }
    

因此,问题在于如何初始化cameraViewControllerprofileViewController。它们是在选项卡栏视图控制器显示之前设置的吗?如果是这样,我建议在您的类中添加自定义init


cameraViewController和profileViewController实际上是Storyboard中的自定义UIViewControllers。那么我想第一个选项应该是最好的吧? - Superian007
请问您能解释一下为什么最后一个选项是糟糕的设计吗? - Superian007
仅仅我的个人观点:你应该确保在 viewDidLoad 中这些变量包含了什么。如果它们对于 TabBarViewController 类至关重要,那么它们应该在那里被设置为非空,并且您应该百分之百确定这一点!现在,如果 TabBarViewController 是一个非常通用的类,并且可以在有或没有这两个视图控制器的情况下工作,那么情况就不同了。但是根据您的问题,我假设它们是必需的 :) - fabian789
你要在哪里以及如何设置变量? - fabian789
现在cameraViewControllerprofileViewController都在required init (coder aDecoder: NSCoder) {}函数中设置。我使用storyboard.instantiateViewControllerWithIdentifier()来实例化这些视图控制器。 - Superian007
1
听起来很完美!为了明确地表明你是在类内部设置它们,你可以标记它们为private(set)。这只是一个提示。 - fabian789

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接