您的位置:首页 > 其它

ViewController控制器的多种创建方式

2016-07-10 00:22 381 查看
    
第一种方式: 
使用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ViewController