1

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.

Adama
  • 1,101
  • 8
  • 26

1 Answers1

-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."

Adama
  • 1,101
  • 8
  • 26
  • The thing is, that's the wrong answer. You should not force premature layout. The problem was merely that you were logging the frame too soon. The view _will_ be laid out correctly; layout _will_ happen. So just don't log the frame until after that happens. The signal that it has happened is `viewDidLayoutSubviews`. – matt Jul 18 '15 at 18:17
  • Yeah you're right -- I've since learned that I need to wait for viewDidLayoutSubviews to be called before messing with constraints or graphics in general. Views aren't always set properly when being accessed during ViewDidLoad (like I was trying above). – Adama Jul 18 '15 at 18:19
  • Correct. So it would be better if you substituted that for your answer above! :) – matt Jul 18 '15 at 18:20
  • I don't care how many reputation points Matt Neuburg has, he deserves more! Once again he has saved me hours of work, and everyone should buy his books!! – Michael Rogers Nov 28 '15 at 22:54