【问题标题】:does not have a member 'instantiateWithOwner'没有成员“instantiateWithOwner”
【发布时间】:2015-02-02 13:01:44
【问题描述】:

我正在尝试制作一个弹出窗口,就像我在 previous question 中描述的那样。我实际上得到了答案,但现在我有一个新问题。如果我不制作instantiateWithOwner,我可以让视图出现,但它没有响应任何东西(只是冻结)。

简而言之,我建立了一个“popup.xib”文件,它只是一个带有按钮和标签的视图。我下面的代码应该让它随着按钮的点击而出现和消失。

我已经阅读了 instantiateWithOwner 将视图连接到它的回调按钮的所有魔法的文档,因此当它不在代码中时没有任何事情发生是有道理的。 (reference)

问题是,如果我将它包含在我的代码中,我会收到编译器错误'PopupViewConrtoller' does not have a member named 'instantiateWithOwner'

我尝试搜索自动完成列表,但没有找到类似的东西。

我的代码:

ViewController.swift

import UIKit

class ViewController: UIViewController {

    @IBAction func showPopup(sender: AnyObject) {
         // This line makes it appear on the screen, but not respond to anything.
        var x = PickerPopupViewConrtoller(nibName: "PickerPopup", bundle: nil)
         // This line does not compile.
        var x = PickerPopupViewConrtoller(nibName: "PickerPopup", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as? PickerPopupViewConrtoller

        x.show(self.view)
    }
}

PopupViewController

import UIKit

class PickerPopupViewConrtoller : UIViewController {

    func show(tView : UIView) {
        tView.addSubview(self.view)
    }

    @IBAction func done(sender: AnyObject) {
        self.view.removeFromSuperview()
    }

}

【问题讨论】:

    标签: ios xcode swift ios8 xcode6


    【解决方案1】:

    是的,没错,instantiateWithOwner 不是 UIViewController 方法,而是UINib 方法。 您必须创建一个 UINib 对象,然后将其转换为您的 UIViewController 类

    例如:

    UINib( nibName: nibNamed, bundle: bundle).instantiateWithOwner(nil, options: nil)[0] as? UIViewController
    

    这就是我使用我在previous answer 中编写的扩展名的原因,它更容易阅读。

    【讨论】:

    • 别担心,我认为这些是开始使用新语言或新 IDE 时的常见错误;)
    【解决方案2】:

    instantiateWithOwnerUINib 上的一个方法。您在 UIViewController 实例上调用它。

    正确的代码如下:

    UINib(nibName: 'PickerPopup', bundle: UIBundle.mainBundle().instantiateWithOwner(nil, options: nil)[0] as? PickerPopupViewController
    

    instantiateWithOwner 方法实际上会调用 PickerPopupViewController 构造函数 (PickerPopupViewController.init(coder:))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 2018-09-29
      • 2017-06-15
      • 2017-02-25
      相关资源
      最近更新 更多