3

I'm using a UILaber showing a second countdown in a very large font (size 240). The displayed string is formatted "xxx.xx", with x's being characters 0-9. I want to align the text to the dot-chatecter (.) in the string that showing in the label. I use textAlignment as .Center in the label, but some strings differ in actual displayed length, causing the dot-character to be shifted left and right when the string is updated. F.x. the textContainer for a "1" is smaller than an "8".

Is it possible to do this kind of character allignment?

Center aligened UILabel

Wiingaard
  • 4,150
  • 4
  • 35
  • 67
  • 2
    This doesn't answer your question, but here is an alternative. Use two labels, one for the three whole number digits and one for the two fraction digits. Put an image of a dot (or however you want to make the dot) in between the two labels. Then you can vertically align the dots, right-align the whole number labels on the left side of the dots, and left-align the fraction labels on the right side of the dots. – keithbhunter Oct 10 '16 at 18:04

3 Answers3

2

Interesting Question mate:

Please find a solution below:

Storyboard using Stacks

Basically what i've done here is:

  1. Using Storyboard i've taken 3 Vertical Stack Views inside a Horizontal Stack View.
  2. Just center align the second vertical stack view with static width and other stack views will adjust accordingly.
  3. Rest you can follow the screenshot attached for constraints.

No constraints required for labels, just text align according to your need.

Cheers!

Annie Gupta
  • 2,786
  • 15
  • 23
1
let attributedStringOne = NSAttributedString.init(string: "XXX", attributes: [NSAttributedStringKey.baselineOffset: 0])
let attributedStringTwo = NSAttributedString.init(string: ".", attributes: [NSAttributedStringKey.baselineOffset: label.frame.height / 4])
let attributedText = NSMutableAttributedString.init()
attributedText.append(attributedStringOne)
attributedText.append(attributedStringTwo)

label.attributedText = attributedText

baselineOffset is NSNumber type. So you can set how much you want from baseline.

Balaji G
  • 77
  • 5
0
  1. attach three labels together..
  2. label1|labelDot|label2 which will be matching your XX.XXX
  3. right align your label1, fix your labelDot, left align your label2
Developer Sheldon
  • 2,140
  • 1
  • 11
  • 17