【问题标题】:Swift view controller initializer issueSwift 视图控制器初始化程序问题
【发布时间】:2016-04-26 14:08:58
【问题描述】:

我有一个视图控制器 A,它在情节提要中有一个 xib。 然后我从 A 继承 B。

现在我想展示一个 B 的视图控制器。

如果我这样做

self.presentViewaController(B.init(), animated: true)

它实际上正在工作,但没有加载 xib。 该应用程序将崩溃,说 collectionView 为零。 假设 xib 有一个 collectionView,并且在 A 类中:

class A: UIViewController {
    @IBOutlet weak var collectionView: UICollectionView!
}

class B: A {
    //Should be empty right? since it inherits from A,
   // but the collectionView from super class is not initialized.
}

如何解决这个问题,以便在实例化 B 时,可以初始化 collectionView?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您应该像这样实例化并保留对 ViewController 的引用:

    var viewController = someViewController(nibName: "SomeViewController", bundle: nil)
    

    然后像这样呈现:

    self.presentViewController(viewController, animated: true)
    

    你当然可以像这样简单地呈现,但它恶心

    self.presentViewController(someViewController(nibName: "SomeViewController", bundle: nil), animated: true)
    

    您可能需要也可能不需要跟踪您的 ViewController,但这会带来灵活性。

    此外,您应该检查委托模式范例,重要的是呈现子 ViewController 的同一个 ViewController 也会关闭子。而不是孩子“自我毁灭”的替代方案。

    【讨论】:

    • 我试过了。它说“加载了“XXViewController”笔尖,但未设置视图出口。”不知道为什么它在 Swift 中如此严格。有什么想法吗?
    • 既然子类没有xib,是不是outlet没有设置的原因?
    • @BabyShung 确保笔尖出口设置正确,特别是视图。
    • 没有工作,现在我只需要通过代码添加collectionview
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 2010-10-24
    • 1970-01-01
    相关资源
    最近更新 更多