没有成员“instantiateWithOwner”
我正在尝试制作一个像我之前提到的问题中描述的popup窗口。 我其实有一个答案,但现在我有一个新的问题。 我可以让视图出现,如果我不做instantiateWithOwner
,但它不响应任何东西(只是冻结)。
总之,我已经build立了一个'popup.xib'文件,它只是一个带有button和标签的视图。 我的下面的代码应该使它出现和button点击消失。
我已经阅读了instantiateWithOwner
将视图连接到它的callbackbutton的所有魔术的文档,所以当它不在代码中时没有任何反应。 ( 参考 )
事情是,如果我包括它在我的代码,我得到一个编译器错误'PopupViewConrtoller' does not have a member named 'instantiateWithOwner'
。
我试图search自动完成列表,但没有发现类似的东西。
我的代码:
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() } }
是的,这是正确的, instantiateWithOwner
不是一个UIViewController方法,它是一个UINib方法。 您必须创build一个UINib对象,然后将其转换为您的UIViewController类
例如:
UINib( nibName: nibNamed, bundle: bundle).instantiateWithOwner(nil, options: nil)[0] as? UIViewController
这就是为什么我使用前面的答案写的扩展,它更容易,更可读。
instantiateWithOwner
是UINib
上的一个方法。 你在一个UIViewController
实例上调用它。
正确的代码将沿着以下几行:
UINib(nibName: 'PickerPopup', bundle: UIBundle.mainBundle().instantiateWithOwner(nil, options: nil)[0] as? PickerPopupViewController
instantiateWithOwner
方法实际上会调用PickerPopupViewController
构造函数( PickerPopupViewController.init(coder:)
)