简体   繁体   中英

Align UILabel text to a specific character

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. Fx the textContainer for a "1" is smaller than an "8".

Is it possible to do this kind of character allignment?

中心是UILabel的中心

Interesting Question mate:

Please find a solution below:

故事板使用堆栈

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!

  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
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM