【发布时间】:2014-03-01 10:44:59
【问题描述】:
我的应用程序中有一个秒表功能,它使用居中属性UILabel 和按比例间隔的字体来呈现时间。每次增加标签的宽度都会发生变化,从而产生弹跳效果,在快速运行时看起来尤其糟糕。这是example。
我该如何解决这个问题?
iOS 9 更新
现在是单线:
UIFont.monospacedDigitSystemFontOfSize(17, weight: UIFontWeightRegular)
另外,我上次尝试时,下面的解决方案不适用于 iOS 9。在标题中绊倒之前浪费了相当多的时间调试。
解决方案
在 iOS 7 中使用 Text Kit 变得微不足道。
确保核心文本已导入:
#import <CoreText/CoreText.h>
创建一个将比例数字转换为等宽数字的设置:
NSArray *monospacedSetting = @[@{UIFontFeatureTypeIdentifierKey: @(kNumberSpacingType),
UIFontFeatureSelectorIdentifierKey: @(kMonospacedNumbersSelector)}];
通过附加UILabel当前使用的字体描述符来创建一个新的字体描述符:
UIFontDescriptor *newDescriptor = [[timeLabel.font fontDescriptor] fontDescriptorByAddingAttributes:@{UIFontDescriptorFeatureSettingsAttribute: monospacedSetting}];
更新标签的字体:
// Size 0 to use previously set font size
timeLabel.font = [UIFont fontWithDescriptor:newDescriptor size:0];
【问题讨论】:
-
贴出绘制文字的相关代码。
-
这对于 iOS 9 也是一个很好的解决方案,其中标准系统字体已更改为 San Fransisco 并且具有比例宽度数字
标签: objective-c swift nsstring nsattributedstring core-text