【问题标题】:How to stop a time UILabel from resizing at every time increment?如何阻止时间 UILabel 在每次增量时调整大小?
【发布时间】: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


【解决方案1】:

对于未来的读者:

这是在旧金山的 iOS 9 上启用等宽数字的方法:

let originalFont = UIFont.systemFontOfSize(17)
let originalFontDescriptor = originalFont.fontDescriptor()

let fontDescriptorFeatureSettings = [
    [
    UIFontFeatureTypeIdentifierKey: kNumberSpacingType,
    UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector
    ]
]

let fontDescriptorAttributes = [UIFontDescriptorFeatureSettingsAttribute: fontDescriptorFeatureSettings]    
let fontDescriptor = originalFontDescriptor.fontDescriptorByAddingAttributes(fontDescriptorAttributes)
let font = UIFont(descriptor: fontDescriptor, size: 0)

编辑:

也可以在 GitHub 上找到: https://github.com/salutis/swift-font-monospaced-digits

【讨论】:

  • 在 Swift 2.0 中工作。谢谢!我使用包含您的代码的函数 monospacedFont 扩展了 UIFont,使用 self 作为 originalFont。这样我就可以轻松获得应用程序中任何标签的等宽版本。
  • @ObjectiveTC 是的,这里也一样。
【解决方案2】:

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

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

return [UIFont fontWithDescriptor:[[self fontDescriptor] fontDescriptorByAddingAttributes:@{UIFontDescriptorFeatureSettingsAttribute : setting}] size:0.0];

【讨论】:

    猜你喜欢
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多