presentViewController 给出错误

presentViewController gives Error

这是我的第一个问题,所以格式可能不是最好的。

在我的应用程序中,我想显示下一个屏幕,这个单独使用时工作正常,所以这里应该没有问题。 我正在使用以下代码进行转换

let dataViewController = self.storyboard?.instantiateViewControllerWithIdentifier("Data")

            self.presentViewController(dataViewController, animated: true, completion: nil)

在第二行 self.presentViewController 我收到错误消息:

Cannot convert the expression's type '(AnyObject?, animated: BooleanLiteralConvertible, completion: NilLiteralConvertible)' to type 'BooleanLiteralConvertible'

我找到的唯一答案是函数是 presentViewController 而不是 presentedViewController,其中一个也有同样的错误。我不得不承认我确实遇到了那个问题。但是在代码中修复此错误后,错误消息并没有消失。 任何人都可以告诉我正确的搜索方向或者有人得到答案吗?

您需要指定 instantiateViewControllerWithIdentifier 的预期类型,因此在获取视图控制器时使用以下行:

let dataViewController = self.storyboard?.instantiateViewControllerWithIdentifier("Data") as UIViewController?

'as' 关键字通知编译器您在 return(又名转换)中期望的真实类型是什么。

instantiateViewControllerWithIdentifier returns 类型 AnyObject 的对象。由于您没有自己指定类型 AnyObject (相当于 ObjC 中的 id )将被使用。

presentViewController 需要一个 UIViewController 实例,而你却给他 AnyObject,因此错误