在另一个 UIViewController init 中初始化自定义 UIViewController

Initialize Custom UIViewController in another's UIViewController init

我有这些自定义 UIViewController、LoadingViewController 和 LoadableViewController,我 LoadableViewController 需要在 startLoading 函数时显示 LoadingViewController 或在 stopLoading 函数时关闭它。我的尝试如下,但我不确定如何在初始化程序中为 loadingViewController 声明变量,因为它已经在情节提要中定义并将由情节提要分配,我不想无缘无故地双重分配它(意思是在 init.

中添加一个 loadingViewController = LoadingViewController() )
import UIKit

class LoadableViewController: UIViewController {

    var loadingViewController: LoadingViewController

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func viewDidAppear(animated: Bool) {
        loadingViewController = storyboard?.instantiateViewControllerWithIdentifier("LoadingiewController") as! LoadingViewController
    }

    func stopLoading() {
        loadingViewController.dismissViewControllerAnimated(true, completion: nil)
    }

    func startLoading() {
        presentViewController(loadingViewController, animated: true, completion: nil)
    }
}

我觉得一切都很好。不应该有双重分配,因为每次出现视图时,您都会覆盖之前的 self.loadingViewController 分配,ARC 将垃圾收集旧值。

不需要 self.loadingViewController = LoadingViewController(),因为此实例不会知道您在故事板上使用 IBOutlet 创建的界面。当您使用 instantiateViewControllerWithIdentifier 时,将使用您在 Interface Builder 中将此 class 关联的 UI 个元素创建 LoadingViewController 的实例。