如何阻止时间UILabel在每个时间增量上调整大小? [英] How to stop a time UILabel from resizing at every time increment?
问题描述
我的应用程序中具有秒表功能,该功能使用居中的属性UILabel
和比例间隔的字体来呈现时间.每次增加标签宽度时,都会产生弹跳效果,在快速移动时效果特别差.这是一个示例.
I have a stopwatch feature in my app that uses a centered attributed UILabel
with a proportionally spaced font to render time. At every time increment the width of the label changes, creating a bouncing effect that looks especially bad at fast speeds. Here is an example.
我该如何解决?
iOS 9 UPDATE
现在它是单线的:
UIFont.monospacedDigitSystemFontOfSize(17, weight: UIFontWeightRegular)
此外,我上次尝试使用以下解决方案不适用于iOS9.在将其绊到标题中之前,浪费了很多时间进行调试.
Also, last time I tried, the solution below did not work for iOS 9. Wasted quite a bit of time debugging before stumbling on this in the header.
解决方案
事实证明,在iOS 7中使用文本工具包显得微不足道.
Turned out to be trivial with Text Kit in iOS 7.
确保已导入核心文本:
#import <CoreText/CoreText.h>
创建一个将比例数字转换为等距的设置:
Create a setting that converts proportional numbers into monospaced:
NSArray *monospacedSetting = @[@{UIFontFeatureTypeIdentifierKey: @(kNumberSpacingType),
UIFontFeatureSelectorIdentifierKey: @(kMonospacedNumbersSelector)}];
通过添加UILabel
使用的当前字体描述符来创建新的字体描述符:
Create a new font descriptor by appending the current one used by UILabel
:
UIFontDescriptor *newDescriptor = [[timeLabel.font fontDescriptor] fontDescriptorByAddingAttributes:@{UIFontDescriptorFeatureSettingsAttribute: monospacedSetting}];
更新标签的字体:
// Size 0 to use previously set font size
timeLabel.font = [UIFont fontWithDescriptor:newDescriptor size:0];
推荐答案
在创建强制使用等宽数字的字体时,请使用等宽字体或传递参数:
Use a monospaced font or pass parameters when creating the font which force monospaced numbers:
//kNumberSpacingType 6
//kMonospacedNumbersSelector 0
NSArray *setting = @[
@{
UIFontFeatureTypeIdentifierKey: @(6),
UIFontFeatureSelectorIdentifierKey: @(0)
}
];
return [UIFont fontWithDescriptor:[[self fontDescriptor] fontDescriptorByAddingAttributes:@{UIFontDescriptorFeatureSettingsAttribute : setting}] size:0.0];
这篇关于如何阻止时间UILabel在每个时间增量上调整大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!