iosxcodeswiftuiuikitswiftui-alignment-guide

How to align two UILabels on the Y axis of the center of the first line of text


please see the image below for two examples of what is to be achived

UILabels to be aligned

the alignment should be on the Center Y of the first lines of each UILabels and should work regardless of font size or font. currently we have implemented this with different constraints to the top of the super view for different font and font size combinations.

the constraint to align the center of the two UILabels does not work since the text of the second UILabel is not fixed and can have several lines.

also the text is dynamic, so it is not known where the text will wrap to create the first line, thus it cannot be shown in an one line UILabel with the rest of the text in another one below.

currently this is implemented using UIKit, but if there is an easy solution in SwiftUI we can put these two labels in a SwiftUI component. so a SwiftUI solution would also be welcomed.


Solution

  • Your comments said "it should be on the glyphs" ... but, without additional information, my guess is that "real world" usage would not really need that level of precision.

    For example:

    enter image description here

    While the glyphs are not perfectly center-Y aligned, it seems unlikely you'd run into a case where the first line of the "rightLabel" is " ' " ' " or . , . , ..

    This layout can be easily done with only a few constraints - no need to do any calculations:

    enter image description here

    The "Positioning" label would, of course, be set .hidden = true so it would never be seen.

    If you really, really want glyph-precision, you'll need to calculate

    and then position the two labels accordingly, or use Core Text to draw the text (instead of using UILabel).

    Probably more work than necessary -- unless your actual use-case demands it.