Search code examples
iosxcodeconstraints

Ambiguous constraint for UITableView when width >= and <=


Trying to set table view width between 290 and 460 points. It's pretty enough to fir content for the small screens and looks good for the big ones, like iPad Pro. Also I want to have leading and trailing space >= 20.

Today's the second day I've tried to fix "inequality constraint ambiguity"... Thanks for the helping!

I'm new in iOS dev so please do not kick me too much :)

enter image description here enter image description here enter image description here The difference between width for smaller and bigger devices


Solution

  • If I understand your goal correctly, you want your table view to be:

    • 20-pts Leading and Trailing
    • unless that makes the table view wider than 460-pts
    • in which case the table view should be centered horizontally

    So, to recap my comment... your constraints say to:

    • Center the table view horizontally
    • make Leading and Trailing >= 20-pts
    • make Width between 290 and 460

    The problem is that you haven't told auto-layout where between 290 and 460 you want the width to end up.

    So, you need a couple more constraints.

    Start simple... tableView constrained 20-pts Top / Leading / Trailing and Zero-pts Bottom (all to Safe Area, of course):

    enter image description here

    Next, add a second set of 20-pt Leading and Trailing constraints:

    enter image description here

    Now set one pair to >=, and give the other pair a Priority less-than required:

    enter image description here

    The Default High 750 priority on the = pair of Leading/Trailing constraints tells auto-layout to "try to pull the sides to 20-pts from the edges, but allow that to break if a conflicting constraint has a higher priority", and the Required 1000 priority on the >= pair gives us a minimum of 20-pts on each side.

    If we switch to Landscape orientation (iPhone 11), everything looks the same... 20-pts Top / Leading / Trailing and Zero-pts Bottom:

    enter image description here

    But... your goal is a max-width of 460, so let's add a Width constraint of <= 460:

    enter image description here

    We see Red issues with the constraints, because we still haven't given auto-layout quite enough information - so, we'll add a Horizontal Center constraint:

    enter image description here

    and here's how it looks on a 9.7" iPad:

    enter image description here

    We don't need -- and don't want -- the >= 290 Width constraint. The = 20 constraints will handle that. And, while unlikely these days, if your app ends up on an iPhone 4s or 1st-gen SE, the view width is only 320... and 290 + 20 + 20 == 330 and you'd have constraint conflicts.