ViewController控制器的多種創建方式

     第一種方式 使用class 創建控制器
    
     ViewController *controller = [[ViewController alloc] init];
     
   
   
   
    
第二種方式 使用storyboard
    
    
// 實例化 storyboard對象
     UIStoryboard *storyboard = [UIStoryboard storyboardWithName:
@"Main" bundle:nil];
    
    
// 取出storyboard中的 控制器 , 使用這種方式實例化控制器的時候, 箭頭必須在,如果不存在, 就會加載不到控制器
    
UIViewController *controller = [storyboard instantiateInitialViewController];
    
     
   
   
    
第三種: 通過 storyboard storyboard ID
    
     UIStoryboard *storyboard = [UIStoryboard storyboardWithName:
@"Main" bundle:nil];
    
    
UIViewController *controller = [storyboard instantiateViewControllerWithIdentifier:@"bigfang"];
     
   
   
    
第四種: 加載xib
     UIViewController *controller = [[NSBundle mainBundle] loadNibNamed:
@"LoadXib" owner:nil options:nil].lastObject;
     
   
   
    
第五種: 實例化xib

     UIViewController *controller = [[UIViewController alloc] initWithNibName:
@"IntinalTest" bundle:nil];
    
     在此附上常見的兩個BUG:
    1. xib中沒有view存在
     reason:
 '-[UIViewController _loadViewFromNibNamed:bundle:] was unable to load a nib named "IntinalTest"'
    
    2. view
沒有進行關聯
    
     reason:
 '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "IntinalTest" nib but the view outlet was not set.'
   
   
    
第六種: 和同類名xib(不使用storyboard)
    
// 如果存在和類名相同的xib , 通過 alloc init 方法,內部會優先加載xib
     TestViewController *controller = [[TestViewController alloc] init];
   
   
// 1. 實例化一個window
   
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
   
   
self.window.backgroundColor = [UIColor whiteColor];
   
   
   
// 2. 實例化控制器
   
   
// 如果存在和類名相同的xib , 通過 alloc init 方法,內部會優先加載xib
   
TestViewController *controller = [[TestViewController alloc] init];
   
   
   
   
// 3. 設置window的根控制器
   
self.window.rootViewController = controller;
   
   
   
// 4. window成爲主窗口並可見
    [self.window makeKeyAndVisible];


注意:我們使用storyboard創建控制器的時候,其實storyboard幫我們自動加載了UIWindow,所以當我們純代碼創建控制器的時候,需要自己實例化UIWindow


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章