How to get monospaced numbers in UILabel on iOS 9

前端 未结 8 1200
囚心锁ツ
囚心锁ツ 2020-12-13 06:52

At WWDC 2015, there was a session about the new “San Francisco” system font in iOS 9. It uses proportional number rendering instead of monospaced numbers by default when lin

8条回答
  •  孤街浪徒
    2020-12-13 07:21

    Note: The method in the currently accepted answer has started crashing for me in Xcode 7.3 (Swift 2.2), only in Release builds. Eliminating the intermediary monospacedDigitFontDescriptor extension variable fixes the issue.

    extension UIFont {
        var monospacedDigitFont: UIFont {
            let fontDescriptorFeatureSettings = [[UIFontFeatureTypeIdentifierKey: kNumberSpacingType, UIFontFeatureSelectorIdentifierKey: kMonospacedNumbersSelector]]
            let fontDescriptorAttributes = [UIFontDescriptorFeatureSettingsAttribute: fontDescriptorFeatureSettings]
            let oldFontDescriptor = fontDescriptor()
            let newFontDescriptor = oldFontDescriptor.fontDescriptorByAddingAttributes(fontDescriptorAttributes)
    
            return UIFont(descriptor: newFontDescriptor, size: 0)
        }
    }
    

提交回复
热议问题