iOS Monospaced Custom Font

前端 未结 3 1889
生来不讨喜
生来不讨喜 2021-01-24 09:08

I have a custom font included in my Xcode 7, iOS 9 targeted project. I want to make the font monospaced. I tried this, and didn\'t work:

let originalFont = UIF         


        
3条回答
  •  失恋的感觉
    2021-01-24 09:34

    My following answer is only making numbers (not the whole font) of an existing font monospaced (if the font supports it)

    At least I was searching for making numbers monospaced when finding this Thread. So I hope it will help although it answers another question.

    This works just fine, tested on Swift 5 and iOS14+13:

    (As long as "your font is supporting the monospaced digits feature".)

    extension UIFont {
    
        var monospacedDigitFont: UIFont {
            let oldFontDescriptor = fontDescriptor
            let newFontDescriptor = oldFontDescriptor.monospacedDigitFontDescriptor
            return UIFont(descriptor: newFontDescriptor, size: 0)
        }
    
    }
    
    private extension UIFontDescriptor {
    
        var monospacedDigitFontDescriptor: UIFontDescriptor {
            let fontDescriptorFeatureSettings = [[UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType, UIFontDescriptor.FeatureKey.typeIdentifier: kMonospacedNumbersSelector]]
            let fontDescriptorAttributes = [UIFontDescriptor.AttributeName.featureSettings: fontDescriptorFeatureSettings]
            let fontDescriptor = self.addingAttributes(fontDescriptorAttributes)
            return fontDescriptor
        }
    }
    

    Then you can use it on any label like this:

    /// Label with monospacing activated
    myLabel.font = myLabel.font.monospacedDigitFontDescriptor
    
    /// Label with monospacing not activated (default is proportional spacing)
    myLabel.font = myLabel.font
    

    (source: https://blog.usejournal.com/proportional-vs-monospaced-numbers-when-to-use-which-one-in-order-to-avoid-wiggling-labels-e31b1c83e4d0)

提交回复
热议问题