在創(chuàng)建一個(gè) ViewController 的時(shí)候 可以選擇是否創(chuàng)建一個(gè) Xib 文件.如果勾選,就會(huì)創(chuàng)建一個(gè)跟創(chuàng)建 ViewController 同名的一個(gè) xib 的文件,并且被關(guān)聯(lián),在用到這個(gè) ViewController 的時(shí)候,只需用[[ViewController alloc]init] 就可以加載到這個(gè) xib.
但是如果不勾選,而事后再去單獨(dú)創(chuàng)建一個(gè) xib 文件和此 ViewController 做關(guān)聯(lián)的話.這個(gè) xib 的文件名 決定加載 xib 的方法.
1.如果 xib 和 viewController 名字不一樣,比如 viewController 叫做"HomeViewController"? xib 叫做"Test.xib"那么即使關(guān)聯(lián), 用 init 方法創(chuàng)建 ViewController 是不能加載到這個(gè) xib 的.要用到initWithNibName:@"Test" bundle:nil 這個(gè)方法去創(chuàng)建.
2.可以把 xib 的命名和 ViewController 一樣的話,只需 init 方法就可以加載到.原理是ViewController 的 init 內(nèi)部方法中首先會(huì)加載和 viewController 同名的 xib, 如果沒有,則再加載去掉"controller"后的命名的 xib, 如果還是沒有,則nil
例子: ViewController 命名為DemoViewController. 用 init 創(chuàng)建的時(shí)候,第一步尋找 ?命名為DemoViewController 的 xib.第二步 尋找命名為 DemoView 的 xib.如果都沒尋找到 那么不加載任何 xib, 即使有關(guān)聯(lián)
情況1:
DemoViewController 關(guān)聯(lián)上 DemoView.xib, init 方法會(huì)加載此 xib
情況2:
DemoViewController 關(guān)聯(lián)上 DemoViewController.xib,init 方法會(huì)加載此 xib
情況3:
DemoViewController 關(guān)聯(lián)上了 DemoView.xib 和 DemoViewController.xib 兩個(gè) xib 文件,那么 init 方法則會(huì)加載 DemoViewController.xib 的內(nèi)容
情況四:
DemoViewController 關(guān)聯(lián)的 xib 名字叫做 VIewController.xib 那么用 init 方法則不會(huì)加載此 xib, 必須用initWithNibName:@"VIewController" bundle:nil方法才可以加載此 Xib.