Autolayout is not updating frames instantly in iOS

2019-05-31 02:33发布

问题:

I'm using autolayout in XCode6.

I have applied the following constraints to a scrollview.

I have tried to access the frame of this scrollview in -viewDidLoad and -viewWillAppear methods for iPhone 4Inchs device. Here problem is, the scrollview's width is showing 600 in Log. But the width should be 300 in 4Ichs device as i'm using autolayout. Seems autolayout will apply after some time interval. It is showing correct width in -viewDidAppear method as 300.

Is there any way to access the original frames in -viewDidLoad and -viewWillAppear methods ?

Thanks in advance.

回答1:

Auto layout doesn't give you the "right" frame sizes until a layout pass has happened. viewDidLoad is too early, and off the top of my head willAppear might be too. viewDidLayoutSubviews is the right place.



回答2:

Place this code in your viewDidLoad()

self.view.setNeedsLayout();
self.view.layoutIfNeeded();

Before accessing scorllView.frame.size.width



回答3:

From the viewDidLoad and viewWillAppear its shows same as interface builder's dimensions. if you apps relay on scrollView frame(if you want them before viewDidAppear) call viewController instance view method before it presenting.

UIViewController *myVC = [[UIViewController alloc]init];
[myVC view]
[self.navigationController pushViewController:myVC];

But this counting on apps performance.