Search code examples
iosswiftautolayoutconstraints

How can I make constraints that the label does not exceed the center of screen?


How to make constraints for this label to start from left and not exceed the center of the view

I tried a lot but i am not sure how i can make it right without it exceeding the half of screen

Talking about the upper label at right


Solution

  • Your requirements for the label are:

    1. Pin to top and right
    2. Never cross the horizontal center of the screen

    The constraints that you need are:

    1. Top and trailing
    2. Proportional width to superview, with equal-or-less-than 0.5 multiplier

    Image of the constraints

    Here's how you add them:

    1. Select your label
    2. Press the constraints button, then add the top and right constraints
    Add the top and right constraints in popup
    1. Right-click and hold on the label, then drag to the superview (the screen)
    Blue line connecting label and superview
    1. Release, then choose Equal Widths
    2. In the size inspector, find the constraint that was just added. Press Edit, then set the "Constant" to <= and the "Multiplier" to 0.5.
    Configuring popup after selecting the constraint

    That's it!

    400 width superview 200 width 100 width
    Label at right Label still at right, still free space to the left Label at right, but limited to half of the superview's width