iOS防止计时器UILabel在数字改变时"摇动"

Chr*_*att 9 ios autolayout swift adaptive-layout

我有一个UILabel显示定时器输出的格式MM:ss:SS(分钟,秒,厘秒),然而它从左到右"摇动",因为厘秒的宽度改变 - 例如,"11"比"33"窄.

有什么方法可以缓解这个问题吗?我试过把它居中,给它一个固定的宽度,但它们似乎没有帮助.

Ken*_*ses 19

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

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

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


Lan*_*ria 8

我有同样的问题。@KenThomases 答案有效。这是 Swift 版本:

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

IE:

yourLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 19, weight: UIFont.Weight.regular)
Run Code Online (Sandbox Code Playgroud)

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

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

根据this other answer,下面的字体是系统生成的字体,也是等宽的,因此它们也不会晃动:

导游

信使-大胆

Courier-BoldOblique

斜信使

CourierNewPS-BoldItalicMT

CourierNewPS-BoldMT

CourierNewPS-斜体MT

快递新PSMT

Menlo-Bold

Menlo-Bold 斜体

门洛斜体

Menlo-Regular

IE:

// no shaking
yourLabel.font = UIFont(name: "Menlo-Regular", size: 19)
Run Code Online (Sandbox Code Playgroud)

如果您只使用数字,那么HelveticaNeue也是等宽的,它不会抖动,但值得怀疑。在使用此字体之前,请阅读此答案下方评论

IE:

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