skip to Main Content

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?

enter image description here
enter image description here
enter image description here

2

Answers


  1. 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.

    Login or Signup to reply.
  2. A UIButton knows how big it’s going to be in size(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 add centerX & centerY 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 in size(width,height). In this case specifying centerX & centerY is not enough for Autolayout to do the rest, it can’t guess the size of the UIView 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search