Can't add self as subview - when adding xib file as subview

3k Views Asked by At

I'm trying to put a xib file as subview in my master viewController, and I get a really really strange error message;

when I have this code :

class MyViewController: UIInputViewController {

    var mainView           : UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        mainView = UINib(nibName: "MainView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! UIView
        self.view.addSubview(mainView)
    }
}

I have this error message :

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't add self as subview' ***

But when I have this code :

class MyViewController: UIInputViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let subViewsArray = [
                 UINib(nibName: "MainView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! UIView
            ]
        self.view.addSubview(subViewsArray[0])        
    }
}

or simply this one :

class MyViewController: UIInputViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(UINib(nibName: "mainView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as UIView)
    }
}

It's working... So, why the first code isn't working !?

Edit :

And when i'm trying to put two subviews :

class MyViewController: UIInputViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let subViewsArray = [
                 UINib(nibName: "MainView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! UIView,
                 UINib(nibName: "AnotherView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as! UIView
            ]
        self.view.addSubview(subViewsArray[0]) 
        self.view.addSubview(subViewsArray[1])               
    }
}

It's not working anymore with the same error message :

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't add self as subview' ***
0

There are 0 best solutions below