Search code examples
iosxcodeautolayout

Why does Xcode only complain about missing constraints after another one has been set


Help me understand:

When you place any view in the interface builder, Xcode won't complain about missing constraints or ambiguous rules. Only once you set some constraints (but not all to remove every ambiguity), Xcode will notify you of missing constraints and suggest some.

For example: I set a constraint to a view, that centers it horizontally in the superview. Now Xcode complains about a missing rule for the Y position. Why doesn't it just infer that from the current X-Postition as it does, when you don't have any constraints in place?


Solution

  • That's because before adding constraints to the view, Xcode will see it as if you want the view to be at the exact X,Y position. That means no matter what size the container is, the view will always be at the exact coordinate and have the same size.

    However, after adding a few constraints, it means that you want the view to change its size or position according to the container size (which is what autolayout is for), so the constraints you added must provide sufficient information for Xcode to determine its frame.

    For example, if you add only Horizontally in Container constraint without specifying its size or Y coordinate, Xcode can't tell where you want the view to be placed. That's why you're getting the warnings.

    As for the example you mentioned, if you set the view to be centered horizontally in container, as the width of the container gets larger, Xcode can't tell which one you would prefer:

    1. stay at the same X position and increase the width of the view.
    2. preserve the size and increase X.

    Increasing the height of the container will also face a similar problem.

    Hope the explanation helps :)

    Example Photo