Search code examples
iosxcodeautolayoutconstraintsnslayoutconstraint

iOS - Placing two label together in centre of their super view


I have two label, L1 and L2 of variable and nonidentical length. I want to place these two label using constraints in Xcode. If possible i don't want to manipulate constraints programmatically. guidance will be appreciated.

Right image should be the expected output

Right image should be the expected output

Requirements,

  1. Two labels are non identical in width
  2. When running leading space of L1 and trailing space of L2 will be equal
  3. distance between L1 & L2, horizontal space is fixed, 10 px
  4. UIStackView cannot be used

How can I do it from Xcode?


Solution

  • What you can do is put both the UILabel inside a UIView and then:

    • Add a leading, top and bottom to the superView to your HEL UILabel.
    • Add a trailing, top and bottom to the superView to your HEAVENLY UILabel.
    • Add a horizontal spacing of 10 points between your two UILabel

    Now center your UIView horizontally and vertically in the middle of the screen. Set the horizontally in center constraint priority to 250. Add a leading and trailing space of your UIView to its superView with a >= 5 constraint

    Edit: Additionally if the text is too large then the above constraints aren't simply enough to work perfectly (You will have to set the numberOfLines to 0 and wrap mode to wordWrap to display the complete text and go to the next line, of course)! As the UILabels will have their inferred height and inferred width with a priority of 750 and the content compression resistance priority of each UILabel is 750 by default too, Xcode will be confused what to do and rightfully so! What you can do is set the content compression property in attributes inspector to 1000

    enter image description here

    OR

    If you don't wish to tinker with compression resistance (I used to find them scary), what you can also do is add a >= constraint to the width and height both of each UILabel. Giving this constraint will also work to show the complete text no matter how large it be, as explicitly defining height and width has given them a priority of 1000!