【问题标题】:Cannot convert value of type 'testViewController.Type' to expected argument type 'UIViewController'无法将“testViewController.Type”类型的值转换为预期的参数类型“UIViewController”
【发布时间】:2019-04-28 13:55:27
【问题描述】:

我收到以下代码的此错误。我有一个名为“testViewController”的视图控制器类。我试图按下一个按钮并让它出现,但这个错误出现在我的代码中。救命!

self.present(testViewController, animated: true, completion: nil)

我希望这应该显示新的视图控制器,但它没有。

【问题讨论】:

  • 错误很明显:您写了 我有一个名为“testViewController”的视图控制器类,因此您将 type 作为参数而不是一个实例。如果您遵守类名以大写字母开头的命名约定,您可以立即看到错误。
  • 你也可以发布你的testViewController类的定义吗?
  • 我不确定你所说的类的“定义”是什么意思。抱歉,但我对此很陌生,所以我对术语很感兴趣。它实际上是一个新的视图控制器,上面有一个标签,上面写着“嗨”。只是试图确定如何让它在按下按钮时出现,因为堆栈 OF 中发布的代码似乎都没有错误。

标签: ios swift presentviewcontroller


【解决方案1】:

你需要传递一个实例而不是

let vc1 = TestViewController.self // wrong
let vc2 = TestViewController() // right

self.present(vc2, animated: true, completion: nil) // right
self.present(TestViewController, animated: true, completion: nil) // wrong
self.present(vc1, animated: true, completion: nil) // wrong

编辑:如果 vc 在情节提要内,请像加载它一样

let vc = self.storyboard!.instantiateViewController(withIdentifier: "VCID") as! TestViewController
self.present(vc1, animated: true, completion: nil) // right

【讨论】:

  • 我这样做了,它根本没有移动到新的视图控制器,但没有错误出现。
  • 你在故事板中创建TestViewController 吗?
  • 我确实创建了 TestViewController,是的。
【解决方案2】:

我刚刚找到了有效的代码。谢谢大家。这里是:

let testViewController = self.storyboard?.instantiateViewController(withIdentifier: "MyTest") as! testViewController // I created MyTest in the identifier field of the identity inspector.

self.present(testViewController, animated: true)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 2016-07-02
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多