I am following a simple tutorial trying to add an X and Y constraint and am having issues with it.
Here is the tutorial:
https://www.youtube.com/watch?v=emojd8GFB0o
Around 11:07 he adds an X constraint and a Y constraint.
I did exactly what he did except for am trying this on a Container View. and yet I still get error saying that it needs an X and Y constraint. It works perfectly fine on a button.
Please help! What am I doing wrong? How do I get this to work on a Container View?
2
Answers
Buttons have something called an "intrinsic content size", which means they can tell the layout system what their preferred size is, this is calculated from their content (text + image).
Your empty container view has no intrinsic content size, it cannot know how big it is on its own, and so far it only knows it has to be centered in X and Y.
But that’s not enough to know its X and Y position (the position is the coordinates of the top-left corner), because if, for example, the width is the full width of the parent, X would be 0, but if the width is 0, X would be half the width of the parent.
You need to give your view a width and a height, whether you do this by linking its size to the parent, or by using constants, that’s up to you.
A
UIButton
knows how big it’s going to be insize(width,height)
. Try adding a short/long title value to the button and you will see that it will size itself accordingly. So when you addcenterX
¢erY
constraints to button (relative to it’s superview), Autolayout can do the rest of the math.Example – Button is
60x40
and it needs to be in center of the screen both horizontally and vertically.A
UIView
does not know how big it’s going to be insize(width,height)
. In this case specifyingcenterX
¢erY
is not enough for Autolayout to do the rest, it can’t guess the size of theUIView
and hence it can’t calculate where to place your view on screen (without knowing size).You can add
width
&height
constraints to your view and you will see that Autolayout will stop complaining about this.