Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGRect vs constraints in programmatic 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?

like image 959
Danial Kosarifa Avatar asked Oct 21 '25 04:10

Danial Kosarifa


1 Answers

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.

like image 80
LIH Avatar answered Oct 22 '25 19:10

LIH