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

前端 未结 2 1116
一整个雨季
一整个雨季 2021-01-23 03:21

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

2条回答
  •  梦毁少年i
    2021-01-23 04:14

    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

    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!

提交回复
热议问题