Incorrect frame being reported using Autolayout &

2019-09-02 05:04发布

问题:

I've laid out a UIView in my UIViewController. Constrained its height and width, and centered it vertically and horizontally with constraints, but when I log its frame, it reports a location that seems appropriate to the full sizeClass, but not the size of the screen I'm looking at.

For example the default size class UIViewController has a width of 600px, and in that size, my UIView is 150px from the left edge. When I check this distance from the left edge while running in the iphone5 simulator, it still reports 150px.

The weird thing about all of this, is that the UIView itself still appears in the expected (adjusted for screen-size) location.

回答1:

For posterity: the problem I was having -- getting incorrect values when printing the frame of a view -- was caused by accessing that frame during ViewDidLoad. At this point in the ViewController lifecycle all views may have not been laid out.

Therefore, it is safest to access a UIView property/outlet only after ViewDidLayoutSubviews has been called.

I mean, it's right there in the name of the method: "Your views have been laid out... now do stuff with them."