此贴为长期更新帖,主要是是本人在开发中使用AutoLayout遇到的各种问题的集合,特此分享给那些把青春献给ios的开发者们。
你有木有遇到这种情况:
明明在StoryBoard(下文中简称sb)中给UIVIew设置了必要的属性,确定了该控件在sb中的具体位置,示例如下图:
接着在ViewController.h文件中关联下该控件
然后在viewDidLoad方法中去打印该控件的高度
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"view height = %f",_myView.frame.size.height);
}
猜猜结果是多少?
让人无比蛋痛的事情来了:
尼玛,在sb中明明设置了高度为50,怎么打印出来的是1000,肿么回事!!!百思不得其解,终于找到了原因:
在执行ViewDidLoad方法的时候,视图控件在sb中设置的布局约束还没有生效,也就说视图控件是先加载后调整布局,那么控件在什么时候开始执行布局的代码呢,接下来说下,视图控制器(简称vc)中各方法的执行顺序:
1)—>viewDidLoad
2)—>viewWillAppear
3)—>viewWillLayoutSubviews(即将开始执行sb中布局代码)
4)—>viewDidLayoutSubviews(sb中布局代码已经执行完毕)
5)—>viewDidAppear
6)—>viewWillDisappear
7)—>viewDidDisappear
在上述的每个方法中都执行:
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"in viewDidLoad height = %f",_myView.frame.size.height);
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSLog(@"in viewWillAppear height = %f",_myView.frame.size.height);
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
NSLog(@"in viewDidAppear height = %f",_myView.frame.size.height);
}
-(void)viewWillLayoutSubviews{
[super viewWillLayoutSubviews];
NSLog(@"in viewWillLayoutSubviews height = %f",_myView.frame.size.height);
}
-(void)viewDidLayoutSubviews{
[super viewDidLayoutSubviews];
NSLog(@"in viewDidLayoutSubviews height = %f",_myView.frame.size.height);
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
NSLog(@"in viewWillDisappear height = %f",_myView.frame.size.height);
}
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
NSLog(@"in viewDidDisappear height = %f",_myView.frame.size.height);
}
查看输出结果:
由此发现:在sb中给控件设置的布局约束是在viewDidLayoutSubviews后才开始生效的。
得出结论:在sb中使用autolayout布局的时候,如果你在viewDidLoad中去获取控件的宽和高,位置属性等,都是获取不到在sb中设置的具体值的,一定要在viewDidLayoutSubviews之后,才能获取到具体属性值!!!切记,不然会掉到坑里,郁闷半天!