为什么需要 instantiateViewController?

Why instantiateViewContoller is necessary?

为什么我不能使用类似的方法创建视图控制器对象 resultVC = ResultViewController() 而不是下面的方式

        let storyboard = UIStoryboard (name: "Main", bundle: nil)
        let resultVC = storyboard.instantiateViewController(withIdentifier: "ResultViewController") as! ResultViewController

        // Communicate the match
        resultVC.match = self.match
        self.navigationController?.pushViewController(resultVC, animated: true)

使用 resultVC = ResultViewController() 将创建一个 ResultViewController 类型的视图控制器,但没有任何指向您的故事板的链接,这对您来说不太可能有任何用处(如果没有获得这些链接,您为什么要使用故事板?)。您需要从情节提要中对其进行实例化才能获得这些链接。

You use this method to create view controller objects that you want to manipulate and present programmatically in your application. Before you can use this method to retrieve a view controller, you must explicitly tag it with an appropriate identifier string in Interface Builder.

因此,您不只是分配 class,而是将 class 与 Interface Builder 中的专用屏幕相关联。

无论如何,您可以按照自己的意愿创建控制器 resultVC = ResultViewController() 但您应该在代码中创建所有 UI 而不是使用 Interface Builder

一切都取决于你的逻辑。您可以通过三种基本方法创建 UIViewController.

  1. 故事板: 你有故事板,设计你的 VC 并通过故事板实例化它。 在这种情况下,您必须告诉系统您的 VC 在哪个故事板中以及它的 ID 是什么。 正如您在上面的代码中所做的那样。

  2. Xib/Nib: 就像故事板一样,您可以使用 xib/nib 设计您的 VC。这里只需要通过 xib 名称分配 VC。

  3. 程序化: 这里你不需要任何类型的 xib/故事板。你必须通过代码来做每件事。您的 VC 设计将在您各自的 VC 文件中。在这里你只需要分配那个文件。

    • 转介: 要么

区别: Which is more efficient way? StoryBoard or XIB?

还有不明白的再问