How do you balance Auto Layout with creating frame

2019-07-17 06:18发布

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条回答
疯言疯语
2楼-- · 2019-07-17 07:13

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.

查看更多
登录 后发表回答