iOS Prevent timer UILabel 'shaking' when numbers change

↘锁芯ラ 提交于 2019-12-08 17:13:53

问题


I have a UILabel which shows the output of a timer in the format MM:ss:SS (minutes, seconds, centiseconds), however it "shakes" from left to right as the width of the centiseconds changes - "11" is narrower than "33" for example.

Is there any way I can mitigate this? I've tried centring it, giving it a fixed width but they haven't seemed to help.


回答1:


Since iOS 9.0, the system font uses proportional digits. If you want monospaced digits, there's a variant font which you can obtain using +[UIFont monospacedDigitSystemFontOfSize:weight:]. This only works for the system font.

If you want to work with another font, you try to ask for a monospaced variant, but there may not be one. Given a UIFont, you can request its fontDescriptor, then ask that for a similar font descriptor that's monospaced (not just for digits) using -[UIFontDescriptor fontDescriptorWithSymbolicTraits:] and UIFontDescriptorTraitMonoSpace. You can then create a new font by passing the new font descriptor to +[UIFont fontWithDescriptor:size:].

However, I doubt there's a monospace variant of Impact. It's not suitable for your purpose.




回答2:


I had the same problem. @KenThomases answer works. Here's the Swift version:

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

ie:

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

FYI there are other UIFont.Weight weights:

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

According to this other answer the fonts below are system generated fonts that are also monospaced so they won't shake either:

Courier

Courier-Bold

Courier-BoldOblique

Courier-Oblique

CourierNewPS-BoldItalicMT

CourierNewPS-BoldMT

CourierNewPS-ItalicMT

CourierNewPSMT

Menlo-Bold

Menlo-BoldItalic

Menlo-Italic

Menlo-Regular

ie:

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

If your using just numeric digits then HelveticaNeue is also monospaced and it doesn't shake but it's questionable. Read the comments below this answer before using this font.

ie:

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



回答3:


Use A monospaced font, also called a fixed-pitch, fixed-width, or non-proportional font, is a font whose letters and characters each occupy the same amount of horizontal space. Examples of monospaced fonts include Courier, Courier New, Lucida Console, Monaco, and Consolas



来源:https://stackoverflow.com/questions/33800488/ios-prevent-timer-uilabel-shaking-when-numbers-change

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