Danial Kosarifa Danial Kosarifa - 3 months ago 18
iOS Question

CGrect vs constrains in IOS pro programmatical GUI Design?

We use

CGRect
inside a frame specifying the width, height and the exact coordination of the rectangle (shape).

Do I need to specify constrains for the UI elements one by one as well? If yes, why do I need to? How about device rotation (portrait vs. landscape mode)? Do I need to define different positioning?

LIH LIH
Answer

If you are defining constraints you do not have to specify a CGRect frame for your design. In fact best way is to use NSLayoutConstraints. The reason is if you set the CGRect frame, when your device is rotating most of the time your CGRect can be wrong. At least hight and with. But if you use constraints when your device is rotating it will layout the subviews again automatically. Which means the views will rearrange according to the constraints.

When you set the CGRect frame what it does is, it changes the view's position and dimensions regardless of the constraints. Then if you try to call view.layoutIfNeeded() or change the orientation the views will be rearranged according to the constraints regardless the frame you set before.