【问题标题】:Cannot invoke" 'setViewController' with an argument list of type [AnyObject]无法使用 [AnyObject] 类型的参数列表调用“'setViewController'
【发布时间】:2015-08-07 19:44:52
【问题描述】:

“无法调用”“setViewController”,参数列表类型为“([AnyObject],方向:UIPageViewControllerNavigationDirection,动画:Bool,完成:nil)””

我在 Xcode 7 beta 3 的这行代码中遇到了这个错误:

self.pageViewController.setViewControllers(viewControllers as [AnyObject], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)

这是剩下的代码:

pageImages = NSArray(objects:"screenshot01","screenshot02","screenshot03")

        self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("MyPageViewController") as! UIPageViewController

        self.pageViewController.dataSource = self

        var initialContenViewController = self.pageTutorialAtIndex(0) as TutorialPageContentHolderViewController

        var viewControllers = NSArray(object: initialContenViewController)


        self.pageViewController.setViewControllers(viewControllers as [AnyObject], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)

        self.pageViewController.view.frame = CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height-100)

        self.addChildViewController(self.pageViewController)
        self.view.addSubview(self.pageViewController.view)
        self.pageViewController.didMoveToParentViewController(self)

如果我在 Xcode 6 中运行相同的代码并且我不知道原因,我不会收到错误消息。

【问题讨论】:

    标签: ios xcode swift


    【解决方案1】:

    签名看起来像:

    func setViewControllers(_ viewControllers: [UIViewController]?,
                  direction direction: UIPageViewControllerNavigationDirection,
                   animated animated: Bool,
                 completion completion: ((Bool) -> Void)?)
    

    那你为什么要投到[AnyObject]

    试试

    self.pageViewController.setViewControllers(viewControllers as [UIViewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
    

    根据viewControllers 的类型,您可能还需要使用as!

    【讨论】:

    • 谢谢,它现在可以使用 as![UIViewController] 进行编译,但我仍然收到警告“将强制向下转换为 '[UIViewController]' 作为可选将永远不会产生'nil'。刚出好奇,为什么错误只在 Xcode 7 中显示,而不在 Xcode 6 中显示?再次感谢 idmean!
    • @DavideNastasi 它试图告诉你如果viewControllers 确实包含不是UIViewController 的东西,例如Stringas! 将导致程序崩溃,它建议你改为使用as?,因为如果数组无法转换为[UIViewController],则会返回nil,而setViewControllers 将接受nil。如果数组中有不属于它的东西,或者是否可以将 nil 传递给setViewControllers,您必须决定程序是否应该崩溃。
    【解决方案2】:

    在xcode7.0中,可以改成

        self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多