【问题标题】:iOS Prevent timer UILabel 'shaking' when numbers change当数字改变时,iOS防止计时器UILabel“摇晃”
【发布时间】:2016-02-21 09:28:17
【问题描述】:

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

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

【问题讨论】:

  • 为具有最高宽泛可能性的标签提供固定宽度约束。对于 ex 33:33:33 应该完全包含在其中。给标签一些背景颜色。它会在一定程度上解决你的问题
  • 使用 textkit 你可以指定所有的数字应该是等宽的。

标签: ios swift autolayout adaptive-layout


【解决方案1】:

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

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

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

【讨论】:

  • 这也适用于自定义字体吗?在这种情况下,我使用Impact
  • 这正是我的评论的意思,只是找不到足够快 ;)
  • @ChrisByatt 这不适用于没有单间距数字集的字体。
【解决方案2】:

我遇到了同样的问题。 @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-Italic

Menlo-Regular

即:

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

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

即:

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

【讨论】:

    【解决方案3】:

    使用等宽字体,也称为固定间距、固定宽度或非比例字体,是一种字体,其字母和字符各自占据相同数量的水平空间。等宽字体的示例包括 Courier、Courier New、Lucida Console、Monaco 和 Consolas

    【讨论】:

    • Xcode 项目中仅包含 Courier、Courier New。但是,是的,这些字体每个字符的宽度都相同。不错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多