问题
When I'm creating a frame in iOS with CGRectMake()
, be it setting the frame
property or using initWithFrame:
, it asks for the x, y, width and height. I supply these.
But with Auto Layout, I'm next going to say something like: "position its x in the very middle" and "set the width to half the screen", right after I set those with CGRectMake()
likely differently.
What do I set them as in CGRectMake()
? 0? An arbitrary value? Something close to what I want?
回答1:
When using auto-layout, you shouldn't set the frame
property at all. You can set the frame
, but there's no purpose in doing so, and only makes your code misleading as the frame
will be superseded by the dimensions it calculates from the constraints. I would suggest completely defining the dimensions of the controls using constraints and avoid setting the frame
entirely to avoid confusion.
So, if you're creating views programmatically, instead of initWithFrame
, just do init
. Also, do not forget to set translatesAutoresizingMaskIntoConstraints
to NO
, and add all of the appropriate constraints such that the layout is unambiguous, but with no conflicting constraints, either.
来源:https://stackoverflow.com/questions/17003363/how-do-you-balance-auto-layout-with-creating-frames