抱歉,我没有任何代码,但是请多多指教!
我有一个倒数计时器,它在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)也可以解决此问题,但是它们形成了鲜明的对比。
关于ios - 倒数期间iOS UILabel中的小数点对齐?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32994463/