How to stop a time UILabel from resizing at every time increment?

前端 未结 2 1616
旧时难觅i
旧时难觅i 2021-01-04 11:06

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

相关标签:
2条回答
  • 2021-01-04 11:48

    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];
    
    0 讨论(0)
  • 2021-01-04 11:58

    For future readers:

    This is how to enable monospaced numbers on iOS 9 with San Francisco:

    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)
    

    Edit:

    Also available on GitHub: https://github.com/salutis/swift-font-monospaced-digits

    0 讨论(0)
提交回复
热议问题