Search code examples
iosautolayout

My layout constraints are being overridden


I'm trying to display a table view overlaid on top of another view to show a list of auto-complete options, but I'm having trouble getting the table view sized correctly.

I have a very simple UITableView defined in a xib file. I load it, embed it in an existing on-screen view, and programmatically set up layout constraints for leading, trailing, top, and height anchors in this view controller method (code is in C#):

public void EmbedIn(UIView outerView)
{
    outerView.AddSubview(View);

    var constraints = new[]
    {
        View.LeadingAnchor.ConstraintEqualTo(outerView.LeadingAnchor, 8),
        View.TrailingAnchor.ConstraintEqualTo(outerView.TrailingAnchor, 8),
        View.TopAnchor.ConstraintEqualTo(outerView.TopAnchor, 15),
        View.HeightAnchor.ConstraintEqualTo(outerView.HeightAnchor, 0.4f, 0),
    };

    NSLayoutConstraint.ActivateConstraints(constraints);
}

The result is that the table view is too small - it has the same dimensions it had in the xib (except, weirdly, the row dividers continue past the bottom down to where the bottom should be).

When I examine the view hierarchy in Xcode, the table view's constraints looks like this:

Xcode constraints

The four constraints that are active are ones that I did not add, either at runtime or in the xib. The width and height in those match the size of the table view in the xib. My leading, trailing, top, and height constraints are there, and among the other disabled constraints is another set matching the xib dimensions, except this time with midX and midY instead of minX and minY.

I tried removing all of the table view's constraints in viewDidLoad (before adding my own), but the ones I'm trying to get rid of don't seem to exist at that point.

So where are those constraints coming from, and how do I get rid of them?


Solution

  • tableView.translatesAutoresizingMaskIntoConstraints = false