2

我试图将一个 xib 文件作为子视图放在我的主视图控制器中,我收到一条非常奇怪的错误消息;

当我有这个代码时:

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

我有这个错误信息:

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

但是当我有这个代码时:

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

或者只是这个:

class MyViewController: UIInputViewController {

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

它正在工作......那么,为什么第一个代码不起作用!?

编辑 :

当我试图放置两个子视图时:

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

它不再使用相同的错误消息:

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

0 回答 0