ViewController控制器的多种创建方式

来源:互联网 发布:淘宝网内衣专卖 编辑:程序博客网 时间:2024/05/16 11:12
    第一种方式使用class创建控制器
    
     ViewController *controller = [[ViewController alloc] init];
     
   
   
   
    
第二种方式使用storyboard
    
    
// 实例化 storyboard对象
     UIStoryboard *storyboard = [UIStoryboard storyboardWithName:
@"Main"bundle:nil];
    
    
// 取出storyboard中的控制器 , 使用这种方式实例化控制器的时候,箭头必须在,如果不存在,就会加载不到控制器
    
UIViewController*controller = [storyboardinstantiateInitialViewController];
    
     
   
   
    
第三种:通过 storyboard storyboard ID
    
     UIStoryboard *storyboard = [UIStoryboard storyboardWithName:
@"Main"bundle:nil];
    
    
UIViewController*controller = [storyboard instantiateViewControllerWithIdentifier:@"bigfang"];
     
   
   
    
第四种:加载xib
     UIViewController *controller = [[NSBundle mainBundle] loadNibNamed:
@"LoadXib"owner:niloptions: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= [[UIWindowalloc]initWithFrame:[UIScreenmainScreen].bounds];
   
   
self.window.backgroundColor= [UIColorwhiteColor];
   
   
   
// 2. 实例化控制器
   
   
// 如果存在和类名相同的xib ,通过 alloc init方法,内部会优先加载xib
   
TestViewController*controller = [[TestViewController alloc] init];
   
   
   
   
// 3. 设置window的根控制器
   
self.window.rootViewController= controller;
   
   
   
// 4. window成为主窗口并可见
    [self.windowmakeKeyAndVisible];


注意:我们使用storyboard创建控制器的时候,其实storyboard帮我们自动加载了UIWindow,所以当我们纯代码创建控制器的时候,需要自己实例化UIWindow


0 0