倒计时期间 iOS UILabel 中的小数点对齐?

Decimal point alignment in iOS UILabel during countdown?

抱歉,我还没有任何代码,但希望得到一些建议!

我有一个倒数计时器,在 UILabel(10.0、9.9、9.8 等)中显示带一位小数的秒数。它工作正常,但小数点会根据大小小数值略微移动。有没有一种方法可以将 UILabel 中的文本与小数点对齐,或者我应该创建两个标签(一个用于右对齐的秒值,一个用于左对齐的小数值)?

谢谢!

我认为你关于多个标签的建议是完全正确的。 这是一个属性字符串解决方案(对于 m:ss 但它也应该适用于浮点数):

    let string = "\t43:21" // Sample min:sec. Note the leading tab is required in this code.

    let countdownFont = UIFont.systemFontOfSize(13)
    let terminators = NSCharacterSet(charactersInString: "\t:.") // in some locales '.' is used instead of ':'
    let tabStop = NSTextTab(textAlignment: .Right, location: 40, options: [NSTabColumnTerminatorsAttributeName: terminators])

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.tabStops = [tabStop]

    let attributeDictionary: [String: AnyObject] = [NSParagraphStyleAttributeName: paragraphStyle, NSFontAttributeName: countdownFont]
    let attributedString = NSAttributedString(string: string, attributes: attributeDictionary)
    self.countdownLabel.attributedText = attributedString

相关资源:

https://www.objc.io/issues/9-strings/string-rendering/#tables-with-numbers

https://library.oreilly.com/book/0636920034261/programming-ios-8-1st-edition/314.xhtml?ref=toc#_tab_stops

当然,固定宽度的字体,例如 Courier 或 Menlo 也可以解决这个问题,但它们的对比相当明显。