does not have a member 'instantiateWithOwner&#

2019-03-03 07:53发布

问题:

I'm trying to make a popup like I described in my previous question. I actually got an answer, but now I have a new problem. I can make the view appear if I don't make the instantiateWithOwner, but it is not responding to anything (just frozen).

In short, I have set up a 'popup.xib' file, which is just a view with a button and a label. My code below should make it appear and disappear with button clicks.

I have read the documentation that the instantiateWithOwner does all the magic of connecting the view to it's callback buttons, so it makes sense that nothing happens when it's not in the code. (reference)

Thing is that if I do include it in my code, I get a compiler error 'PopupViewConrtoller' does not have a member named 'instantiateWithOwner'.

I have tried searching the auto-complete list, but found nothing similar.

My code:

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()
    }

}

回答1:

Yes it's correct, instantiateWithOwner is not a UIViewController method, it is a UINib method. You have to create a UINib object and then cast it to your UIViewController class

ex:

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

That's why I use the extension I wrote in the previous answer, it's easier and more readable.



回答2:

instantiateWithOwner is a method on UINib. You are calling it on a UIViewController instance.

The correct code would be along the following lines:

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

The instantiateWithOwner method will actually call the PickerPopupViewController constructor (PickerPopupViewController.init(coder:))