1 生命周期
- init方法中view仍然是nil,此时,如果写了self.view,直接调用loadView。
- 看名字也知道,loadView在viewDidLoad之前。
initWithNibName:bundle:
,designated初始化方法
2 代码组织
- init,只有需要传一些参数的时候,才需要 不要出现self.view,只做普通属性赋值(如model,详情页url等)
- viewDidLoad中 组装好subview
- viewWilAppear中 处理数据相关,处理系统级任务(比如statusbar、网络监听等)
- viewDidLayoutSubviews中 处理布局
- subview在getter中初始化
- 瘦身 ViewModel/Present + category、RAC
一个不符合规范的案例,会导致错误。
//first vc
+ (instancetype)initWithUrl:(NSString *)url {ViewController *controller = [ViewController new]; //已经在next vc的init中执行了viewDidLoad,而此时url还没有传过去controller.url = url;return controller;
}//next vc
#pragma mark - life cycle
- (instancetype)init {self = [super init];if(self) {[self.view addSubview: self.webView]; //应该写在viewDidLoad中}return self;
}- (void)viewDidLoad { //下面两句应该写在viewWillAppear:中[self startLoading];[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
}
复制代码
3 一些应用
3.1 ChildVC + ScrollView
比如头条,上面有一个横拉的栏目View,下面才是ChildVC的view 做法:ScrollView + VCs
- ScrollView中实际上是多个childVC的根view
- 创建childVC的时候,设置好frame,包括横向偏移量。
注意
- 因为[scrollView addSubview:childVC.view],已经调用了childVC.view,所以这是已经调用了childVC的loadView和viewDidLoad方法。
addChildViewController
后,childVC的生命周期方法,如viewWillAppear、viewDidAppear等,就跟随父VC了自动处理。
优化:
- 可以使用displayVC,cachedVCs,缓存数组,内存预警或进入后台时清理cachedVCs。
- 点击专栏引发的更换VC,
/添加一个 childViewController
UIViewController *vc = [UIViewController new];
[self addChildViewController:vc];
vc.view.frame = ..;
[self.view addSubview:vc.view];
[vc didMoveToParentViewController:self];//移除一个 childViewController
[vc willMoveToParentViewController:nil];
[vc.view removeFromSuperview];
[vc removeFromParentViewController];
复制代码
3.2 ChildVC + UIPageViewController
实现相册浏览功能,图片放缩
4 通用做法
4.1 隐藏状态栏
#pragma mark - statusbar
-(BOOL)prefersStatusBarHidden {return YES;
}
复制代码