IvanMartinez IvanMartinez - 9 months ago 22
Swift Question

Write one part of a text at the left and second part at the right of a UILabel

Is it possible to write a text on a UILabel such that one part is aligned to the right and another part is aligned to the left?

I want to write this: "Level 1: 55 points"

But I want that "Level 1:" appears at the left of the label and "55 points in the right"

dfd dfd
Answer Source

Poor solution:

Making a UILabel left-justified and putting spaces between what you wish left and right justified. (You'll also wish to choose a fixed pitched font for this also.

You can always subclass UILabel, adding a UILabel as a subview. Make one right-justified and another as left-justified.

Pretty good solution:

Putting two UILabels next to each other with spacing. If you are setting things up for a couple of "combos" like this, it is probably worth doing. Just remember, for iOS it's also good to use auto layout, so maybe you'll want each combo as a cell in a UIStackView.

Good solution:

Subclass UILabel. Add a single UILabel as the right-justified subview inside a subview UILabel that is left justified. The problem here is confusing other developers who may be maintaining things.

Best solution:

Subclass UIView, putting two UILabels as subviews. Now you can create obvious properties (leftText, rightText) for each individual subview along with obvious shared properties (font, font size). As an added bonus you could have each have individual fonts (leftFont, rightFont) instead. Now you are adding constraints to a single view. And if you wish, you can make this IBDesignable/IBInspectable for use in Interface Builder.

IMHO the "pretty good" solution is best if you are working with a single superview that contains - just personal taste - at most 3 combo left/right justified labels. The best solution gives you the most flexibility going forward, and simplifies any multi-view of complicated use.