Decimal point alignment in iOS UILabel during countdown?

独自空忆成欢 提交于 2019-12-02 04:07:05

I think your suggestion of multiple labels is perfectly valid. Here is an attributed string solution (for m:ss but it should work with floating point numbers also):

    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

Related resources:

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

Of course a fixed width font, such as Courier or Menlo could also solve this problem, but they contrast fairly starkly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!