iOS Autolayout情况下,ViewController嵌套时,childViewController的Frame异常问题
近期项目中,使用Storyboard、AutoLayout开发,某个ViewController中嵌套了多个子ViewController,结果在将其加入到父ViewController时,出现坐标异常问题。追踪代码发现,这是因为AutoLayout状态下,获取Frame数据不准确(或时机不正确)导致的,网上找了许久,取长补短,搞到了解决的方法,详细例如以下:
分析:
AutoLayout状态下。运行完viewDidLoad、viewWillAppear等方法后,还会运行viewDidLayoutSubviews方法,而解决这个问题的关键就在这儿。
在这种方法中,我们能够又一次对某个子View。甚至某个ChildViewController的View进行Frame调整。
演示样例代码例如以下:
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
self.contentScrollView.contentSize = CGSizeMake(CGRectGetWidth(self.contentScrollView.frame) * 3, CGRectGetHeight(self.contentScrollView.frame));
if (IOS8) {
CGFloat subView_W = CGRectGetWidth(self.contentScrollView.frame);
for (int i = 0; i < 3; i++) {
UIView *subView = [self.view viewWithTag:SubVC_ViewTag + i];
CGRect subViewFrame = subView.frame;
subViewFrame.origin.x = subView_W * i;
subView.frame = subViewFrame;
}
} //iOS7必须运行
[self.view layoutSubviews];
}
注意:这种方法中,若是iOS7。则必须运行
[self.view layoutSubviews];

浙公网安备 33010602011771号