控制器的创建
- 通过storyboard
// 加载storyboard
// storyboard文件名,不需要带后缀
// nil: [NSBundle mainBundle]
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
// 通过storyboard创建控制器
// instantiateInitialViewController:加载箭头指向的控制器
UIViewController *vc = [storyboard instantiateInitialViewController];
//加载指定标识的控制器
UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"green"];
- 通过xib
// 通过xib创建控制器
YWViewController *vc = [[YWViewController alloc] initWithNibName:@"YWViewController" bundle:nil];
- 注意点
1、需要设置xib的`File's Owner`的Custom Class
2、需要给`File's Owner`的Outlets中的view连线
3、如果没有给nibName传值,那么系统会自动加载
YWViewController.xib
,没有这个会寻找YWView.xib
(这里不清楚什么情况,在我电脑上测试是这样,但是文档中写的是先找YWView.xib
,后找YWViewController.xib
)
If the view controller class name ends with the word ‘Controller’, as in MyViewController, it looks for a nib file whose name matches the class name without the word ‘��Controller’, as in MyView.nib. It looks for a nib file whose name matches the name of the view controller class. For example, if the class name is MyViewController, it looks for a MyViewController.nib file.
4、如果第二点没有连线,报错信息:
reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "YWViewController" nib but the view outlet was not set.'
- 手动创建
YWViewController *vc = [[YWViewController alloc] init];
- 手动创建的麻烦的地方就是所有东西都需要自己去写代码创建
5、使用storyboard创建控制器的时候,通常需要从一个控制器跳转到另一个控制器,这个时候就需要执行一些特殊的方法
//执行跳转
[self performSegueWithIdentifier:@"目标控制器的ID" sender:nil];
// 在执行跳转之前的时候调用
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// 源控制器
segue.sourceViewController
//目标控制器
segue.destinationViewController
}