In iOS Autolayout, the Frame of childViewController is abnormal when ViewController is nested.
In a recent project, we used Storyboard and AutoLayout for development. A ViewController contains multiple child viewcontrollers. As a result, when we add them to the parent ViewController, a coordinate exception occurs. tracking code found that, this is because the Frame data obtained in the AutoLayout status is inaccurate (or the timing is incorrect). After a long time of searching online, I learned from each other and found a solution, as shown below:
Analysis:
After viewDidLoad, viewWillAppear, and other methods are executed in the AutoLayout status, the viewDidLayoutSubviews method is also executed. The key to solving the problem is here.
In this method, we can re-adjust the Frame of a subview or even a ChildViewController View.
The sample code is as follows:
- (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 must execute [self. view layoutSubviews];}
Note: In this method, if it is iOS7, it must be executed
[self.view layoutSubviews];