iOS 当数字改变时阻止计时器 UILabel 'shaking'

iOS Prevent timer UILabel 'shaking' when numbers change

我有一个 UILabel,它以 MM:ss:SS(分、秒、厘秒)的格式显示计时器的输出,但是它 "shakes" 从左到右作为宽度厘秒的变化 - 例如,“11”比“33”窄。

有什么办法可以缓解这种情况吗?我试过将它居中,给它一个固定的宽度,但它们似乎没有帮助。

Use A monospaced字体,也叫固定间距、固定宽度或不成比例的字体,是一种字体,其字母和字符各自占据相同数量的水平space. monospaced 字体的示例包括 Courier、Courier New、Lucida Console、Monaco 和 Consolas

从iOS9.0开始,系统字体使用比例数字。如果您想要等宽数字,可以使用 +[UIFont monospacedDigitSystemFontOfSize:weight:] 获得一种变体字体。这仅适用于系统字体。

如果您想使用另一种字体,您尝试要求等宽变体,但可能没有。给定一个 UIFont,你可以请求它的 fontDescriptor,然后使用 -[UIFontDescriptor fontDescriptorWithSymbolicTraits:]UIFontDescriptorTraitMonoSpace 请求一个类似的等宽字体描述符(不仅仅是数字)。然后,您可以通过将新字体描述符传递给 +[UIFont fontWithDescriptor:size:].

来创建新字体

但是,我怀疑是否存在 Impact 的等宽变体。它不适合您的目的。

我遇到了同样的问题。 @KenThomases 回答有效。这是 Swift 版本:

// replace whatever font your using with this font instead to stop the shaking
UIFont.monospacedDigitSystemFont(ofSize: 19, weight: UIFont.Weight.regular)

即:

yourLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 19, weight: UIFont.Weight.regular)

仅供参考,还有其他 UIFont.Weight 权重:

.black, .bold, .heavy, .light, .medium, .regular, .semibold, .thin, .ultraLight

According to this other answer 下面的字体是系统生成的字体,它们也是 等宽 所以它们也不会抖动:

快递

Courier-Bold

Courier-BoldOblique

Courier-Oblique

CourierNewPS-BoldItalicMT

CourierNewPS-BoldMT

CourierNewPS-ItalicMT

CourierNewPSMT

Menlo-Bold

Menlo-BoldItalic

Menlo-斜体

Menlo-Regular

即:

// no shaking
yourLabel.font = UIFont(name: "Menlo-Regular", size: 19)

如果您只使用数字,那么 HelveticaNeue 也是 monospaced 并且它不会抖动但值得怀疑。使用此字体前请阅读 comments below this answer

即:

// no shaking but apparently you can only use numbers not letters
yourLabel.font = UIFont(name: "HelveticaNeue", size: 19)