iOS Monospaced Custom Font

◇◆丶佛笑我妖孽 提交于 2019-12-02 11:25:18

问题


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 = UIFont(name: "My Custom Font", size: 18)
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)

topLabel.font = font

With or without above code, the label displayed in proper custom font. It's just above code doesn't do anything.


回答1:


The code you are using is not making font monospaced.

It's tweaking font to render digits in monospace mode. So all with this font digits will have same width.

Below is an example with 4 labels, 1 is using custom font Docis Light, 2nd is Docis Light with monospaced digits on, 3rd is system font of same size, 4th is system font with monospaced digits on:

As you see, this custom font already supports monospace digits feature out of the box with no tweak required.

If you need to use monospaced (not just digits) font, you have to use custom monospaced font (designed to be monospaced) or you can use built-in iOS monospaced fonts such as Courier or Menlo (See all available iOS fonts at http://iosfonts.com/)

This is how they look like with same scenario:

With or without tweaking, they are already monospaced and the digits are monospaced as well.

I answered similar question here, probably, I should just link the answer instead of images but it so much more visual.




回答2:


Don't forget to import the header file. Hope it will work. This solution is in Objective-C

#import <CoreTextArcView.h>

UIFont *const existingFont = [UIFont preferredFontForTextStyle:   UIFontTextStyleBody];
UIFontDescriptor *const existingDescriptor = [existingFont fontDescriptor];

NSDictionary *const fontAttributes = @{

UIFontFeatureTypeIdentifierKey 

UIFontDescriptorFeatureSettingsAttribute: @[
 @{
   UIFontFeatureTypeIdentifierKey: @(kNumberSpacingType),
   UIFontFeatureSelectorIdentifierKey: @(kMonospacedNumbersSelector)
  }]
};

UIFontDescriptor *const monospacedDescriptor = [existingDescriptor  fontDescriptorByAddingAttributes: fontAttributes];
UIFont *const proportionalFont = [UIFont fontWithDescriptor: monospacedDescriptor size: [existingFont pointSize]];


来源:https://stackoverflow.com/questions/34571412/ios-monospaced-custom-font

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!