简体   繁体   English

将UILabel文本与特定字符对齐

[英]Align UILabel text to a specific character

I'm using a UILaber showing a second countdown in a very large font (size 240). 我正在使用UILaber以非常大的字体显示第二个倒计时(大小240)。 The displayed string is formatted "xxx.xx", with x's being characters 0-9. 显示的字符串格式为“xxx.xx”,x为字符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. 我在标签中使用textAlignment作为.Center,但是某些字符串的实际显示长度不同,导致点字符在更新字符串时左右移动。 Fx the textContainer for a "1" is smaller than an "8". Fx textContainer为“1”小于“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. 使用Storyboard我在水平堆栈视图中采用了3个垂直堆栈视图。
  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 label1 | labelDot | label2将匹配您的XX.XXX
  3. right align your label1, fix your labelDot, left align your label2 右对齐你的label1,修复你的labelDot,左对齐你的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. baselineOffsetNSNumber类型。 So you can set how much you want from baseline. 因此,您可以根据基线设置所需的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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