iOS 加载视图控制器的三种方式
2019-03-22 本文已影响0人
陈盼同学
加载iOS控制器,有很多种方式,比如直接创建类,或者通过XIB,亦或者通过Storyboard ,下面分别介绍
一、直接初始化
//新建TestViewController类继承ViewController,想拿到这个控制器,直接使用下面代码即可
TestViewController vc = [TestViewController alloc] init];
二、通过storyboard 创建控制器
第1种方式、
新建TestViewController类继承ViewController,假设已经有个storyboard文件叫Main(如果被删了可以新建一个storyboard文件),向Main.storyboard文件里拖了一个控制器视图,同时设置了红框里的class和storyboardID,那么可以通过以下代码初始化TestViewController控制器

//1.先加载storyboard文件(Main是storyboard的文件名)
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//2.通过一个标识"Gray"(控制器里的storyboard ID)初始化对应的控制器
TestViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"Gray"];
第2种方式、
新建TestViewController类继承ViewController,假设已经有个storyboard文件叫Main(如果被删了可以新建一个storyboard文件),向Main.storyboard文件里拖了一个控制器视图,同时设置了红框里的Is Initial View Controller使其控制器视图出现箭头,那么可以通过以下代码初始化TestViewController控制器
//1.先加载storyboard文件(Main是storyboard的文件名)
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//2.初始化“初始控制器”(箭头所指的控制器)
TestViewController *vc = [storyboard instantiateInitialViewController];
三、指定xib文件来创建
新建TestViewController类继承ViewController,新建一个名为TestViewController的xib文件,那么可以通过以下代码初始化控制器
// 通过xib创建控制器
TestViewController *vc = [[TestViewController alloc] initWithNibName:@"TestViewController" bundle:nil];