Decimal point alignment in iOS UILabel during coun

2019-02-28 21:50发布

Sorry I don't have any code yet, but would appreciate some advice!

I have a countdown timer showing seconds with one decimal point in a UILabel (10.0, 9.9, 9.8, etc.). It works fine, but the decimal point moves around slightly depending on the size decimal value. Is there a way to align the text in the UILabel to the decimal point or should I create two labels (one for the seconds value aligned right and one for the decimal value aligned left)?

Thanks!

1条回答
淡お忘
2楼-- · 2019-02-28 22:41

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.

查看更多
登录 后发表回答