JokeMines
JokeMines

Reputation: 29

Basic Autolayout issue, resizing button after setting constraints

Sorry for the super basic question, I'm not understanding why (or how) Autolayout automatically resizes buttons/labels after setting constraints to the safe area/view.

Here is a short video demonstrating my exact problem. I want to keep a 200x100 button centered horizontally near the top of the screen, why does it resize itself after setting constraints?

If anyone could explain/point me to a good guide for getting started with auto layout it would be greatly appreciated!

Upvotes: -1

Views: 46

Answers (3)

matt
matt

Reputation: 535989

The two basic rules of autolayout are:

  1. Autolayout and frame/size are opposites. You can only use one of them.

  2. If you choose to use autolayout, you must completely determine both position and size using autolayout.

So, at first in your video you are using frame/size. So the button obeys your size settings.

But then you come along and add some constraints. At that moment, you are using autolayout — and your frame/size settings cease to mean anything.

Well, the rule for something like a button or a label is that unless you explicitly set width and height constraints with the desired Constant values, it will size itself to its contents as an automatic fallback (using its own internal constraints that you can’t see). So that is what it does.

The easiest way to add a width or height constraint is to control-drag internally inside the button, horizontally or vertically. But you still might need to set the Constant back to what you wanted it to be (in the constraint's size inspector).

Upvotes: 1

David Chopin
David Chopin

Reputation: 3064

You need to set constraints for the width and height, not simply set the width and height. Setting constraints will ensure that the width and height do not vary from what you set them as.

Check out a demonstration below of how I set the width of a button equal to 200, the height equal to 100, the offset from the safeArea top to 20 and horizontally centering the button:

Setting autolayout constraints

Upvotes: 2

Zafar Ivaev
Zafar Ivaev

Reputation: 133

You should set the constraints for width and height, not just size in Size Inspector. Make sure you set them as follows: setting constraints

Upvotes: 1

Related Questions