I was trying to create a UI with two labels placed horizontally in parallel to other edges on the screen so that they can grow according to the content they receive.
and
I tried setting up content hugging and compression resistance priority and was able to have labels grow based on content but when either of the labels received even more content, they started overlapping each other.
and
how do set up constraints? in such a way that labels can grow based on the content they receive, if the content is bigger then they should start truncating themselves so there should always be a minimum margin in between so that they don't start overlapping each other and if content for both labels is big enough then they should take up the space divided equally.




The simplest solution is to use a
UIStackView, no code required. Add a horizontalUIStackViewto the storyboard then add the two labels to the stack view.Set desired constraints on the leading and trailing anchors of the stack view to position it in the view controller's view. Add a constraint to just one of the top, bottom, or centerY anchor to position the stack view vertically. The height of the stack view will come from the labels.
Ensure the stack view properties are as follows:
Update the label properties such that the left label has left alignment and the right label has right alignment. Change the Line Break to suit your needs.
That's it. The stack view will, with a distribution of "Fill proportionally", ensure the width of the two labels will be adjusted to match the requirements posted in your question.
If you don't want to use a stack view, there is a way to meet your needs but it does require a bit of code to make it work. There's no way to get the width of the two labels to automatically size proportionally based on the combined width of the labels using just constraints setup in the storyboard.
I created a simple iOS app. Start with a new iOS app project. Add two labels to the view controller's safe area. In the storyboard, add the following constraints:
With those in place you will see something like the following in the storyboard:
In my own test I also set the following label properties:
Note that all other label properties are left as defaults, including the content compression and hugging priorities.
Update ViewController.swift with the following code:
Now connect the two labels to their outlets. Lastly, connect the left label's width constraint to its outlet.
You can now run and test the code with different label values to check the results.