3

I want to detect the style(bold ,heavy, black) of a font. But I can just detect whether the font is bold.

BOOL isBold = (font.fontDescriptor.symbolicTraits & UIFontDescriptorTraitBold)!=0;

There is no black or heavy trait in UIFontDescriptorSymbolicTraits.

A way is to check the font name whether contains 'black' or 'heavy' string, but this seems unreliable.

There is UIFontWeightTrait, but it's just for UIFont systemFontOfSize: weight:

And I want to create my custom font with a style if there is available these style.

tomfriwel
  • 2,575
  • 3
  • 20
  • 47

3 Answers3

3

To check if it's Heavy or Black:

NSString *fontUsage = font.fontDescriptor.fontAttributes[@"NSCTFontUIUsageAttribute"];
if ([fontUsage isEqualToString:@"CTFontHeavyUsage"]) {
    NSLog(@"It's Heavy");
}
else if ([fontUsage isEqualToString:@"CTFontBlackUsage"]) {
    NSLog(@"It's Black");
}

The list of other usage options are very simple, just put usage in format "CTFont......Usage", the list I tested are:

//CTFontUltraLightUsage,CTFontThinUsage,CTFontLightUsage,CTFontMediumUsage,CTFontDemiUsage

And How to create a font with usage, like heavy:

UIFontDescriptor *fontDescriptor = [[UIFontDescriptor alloc] initWithFontAttributes:@{@"NSCTFontUIUsageAttribute":@"CTFontHeavyUsage"}];
UIFont *font = [UIFont fontWithDescriptor:fontDescriptor size:17];

Swift3 version for checking:

if let fontUsage = font.fontDescriptor.fontAttributes["NSCTFontUIUsageAttribute"] as? String {
    if fontUsage == "CTFontHeavyUsage" {
        print("It's Heavy")
    }
    else if fontUsage == "CTFontBlackUsage" {
        print("It's Black")
    }
}
Yun CHEN
  • 6,450
  • 3
  • 30
  • 33
1

Swift Version for detecting Heavy/Black style of font

let fontUsage = font.fontDescriptor.fontAttributes["NSCTFontUIUsageAttribute"] as! String
if fontUsage == "CTFontHeavyUsage"{
    print("It is heavy")
}
else if fontUsage == "CTFontBlackUsage"{
    print("it's black")
}

and to create font with attributes:

let fontDescriptor = UIFontDescriptor(fontAttributes: ["NSCTFontUIUsageAttribute" : "CTFontHeavyUsage"])
let font = UIFont(descriptor: fontDescriptor, size: 17)
Shabir jan
  • 2,295
  • 2
  • 23
  • 37
0

This gives you whether a font is bold or not:

var isBold = label.font.fontDescriptor.symbolicTraits.contains(.traitBold)

Here is some experiement: this gives you the correct answer even if the a bold font is set, or if you set the font's symbolicTraits manually to be bold:

enter image description here

Balazs Nemeth
  • 2,333
  • 19
  • 29