没有会员 'instantiateWithOwner'

does not have a member 'instantiateWithOwner'

我正在尝试制作一个弹出窗口,就像我在 中描述的那样。我实际上得到了答案,但现在我有一个新问题。如果我不创建 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()
    }

}

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

正确的代码如下:

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

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

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

例如:

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

这就是为什么我使用我在 中编写的扩展程序的原因,它更容易和更具可读性。