skip to Main Content

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.

2

Answers


  1. That’s an interesting problem! You can try using the centerYAnchor for the label on the left, and the firstBaselineAnchor for the label on the right… that will align the center Y with the text baseline, which isn’t quite what you want.

    To find the correct offset to apply, you can use the information from UIFont about the size of the characters. I’d probably start with capHeight * 0.5 and see if that looks or feels right. Something like:

    leftLabel.centerYAnchor.constraint(equalTo: rightLabel.firstBaseLineAnchor, constant: rightFont.capHeight * 0.5)
    

    This is a more difficult problem in SwiftUI, I think, because resolved font metrics aren’t directly available to you.

    Login or Signup to reply.
  2. 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

    • the Glyph bounding box for the left-label
    • the Glyph bounding box for first line of the right-label
    • calculate the "character box" offsets to align the Glyph Y-centers

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search