I want to make the first line of those words (I am using UI Label here, or should I use Text View?), in the center of red line, the center of that red line is located at the center of that yellow UIView
I have tried some autolayout configuration but still failed to achieve this
This is an involved process. Take your time to understand the whole logic.
First of all we have some considerations:
We will add a placeholder view to the right hand side of the Yellow view and make them center aligned. Here comes the handy UIStackView
.
We take a UIStackView
with these properties:
Horizontal
Center
Fill
The above stack view uses the Auto Layout:
These are the constraints for the stack view:
Now we will add two views to the stack view with the attributes:
These are the constraints for the two views:
Now comes the label's part. It's a multiline label (number of lines set to 0
) The label will be aligned with the placeholder view by top, leading & trailing constraints. But the top constraints need a slight consideration. The label will have a font size of 20
so that if the top constraint has -13
(not -10
because there is a top padding between the label's frame and label's text) value with the placeholder, then it can be aligned with the horizontal center of the Yellow view.
These are the constraints for the label:
Enough of the talking. I have made a demo which you'll find here. Also keep in mind if you need to control the horizontal space between the yellow view and the label, you can achieve that by changing the spacing value of the stack view.
Also keep in mind that, this implementation is very tightly configured. Anything changes, everything breaks. But if your need is slightly changed so that the first line of the label is vertically aligned (not the horizontal center of the first line) you can forget about the font size of the label and the -13
top constraint's value.
Below is the final output. I added a horizontal redline to indicate the middle of the yellow view.