如何阻止UILabel在每次增量时调整大小?

Ale*_*nko 10 objective-c nsstring nsattributedstring core-text swift

我的应用程序中有一个秒表功能,使用居中UILabel的比例间距字体来渲染时间.每次增加标签的宽度都会发生变化,从而产生一种在快速速度下看起来特别糟糕的弹跳效果.这是一个例子.

我怎样才能解决这个问题?

iOS 9更新

它现在是一个单行:

UIFont.monospacedDigitSystemFontOfSize(17, weight: UIFontWeightRegular)
Run Code Online (Sandbox Code Playgroud)

此外,我上次尝试时,下面的解决方案不适用于iOS 9.浪费了相当多的时间调试之前在标题中遇到这个问题.

在iOS 7中使用Text Kit变得微不足道.

确保导入Core Text:

#import <CoreText/CoreText.h>
Run Code Online (Sandbox Code Playgroud)

创建一个将比例数转换为等宽数字的设置:

NSArray *monospacedSetting = @[@{UIFontFeatureTypeIdentifierKey: @(kNumberSpacingType),
                                 UIFontFeatureSelectorIdentifierKey: @(kMonospacedNumbersSelector)}];
Run Code Online (Sandbox Code Playgroud)

通过附加当前使用的字体描述符来创建新的字体描述符UILabel:

UIFontDescriptor *newDescriptor = [[timeLabel.font fontDescriptor] fontDescriptorByAddingAttributes:@{UIFontDescriptorFeatureSettingsAttribute: monospacedSetting}];
Run Code Online (Sandbox Code Playgroud)

更新标签的字体:

// Size 0 to use previously set font size
timeLabel.font = [UIFont fontWithDescriptor:newDescriptor size:0];
Run Code Online (Sandbox Code Playgroud)

小智 2

在创建强制等宽数字的字体时使用等宽字体或传递参数:

//kNumberSpacingType 6
//kMonospacedNumbersSelector 0
NSArray *setting = @[
                         @{
                             UIFontFeatureTypeIdentifierKey: @(6),
                             UIFontFeatureSelectorIdentifierKey: @(0)
                             }
                         ];

return [UIFont fontWithDescriptor:[[self fontDescriptor] fontDescriptorByAddingAttributes:@{UIFontDescriptorFeatureSettingsAttribute : setting}] size:0.0];
Run Code Online (Sandbox Code Playgroud)