2

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' ***
StrawHara
  • 1,301
  • 19
  • 33
  • try to read this question http://stackoverflow.com/questions/28201249/swift-assign-a-nib-to-self-in-class – wm.p1us Oct 05 '15 at 10:25

0 Answers0