UIFontWeightTrait and UIFontDescriptorFamilyAttribute Ignored when creating UIFont from UIFontDescriptor
I ran into the same issue, and the documentation was not much help. Eventually I figured out that using the family attribute combined with the face attribute worked:
UIFontDescriptor* desc = [UIFontDescriptor fontDescriptorWithFontAttributes:
@{
UIFontDescriptorFamilyAttribute: @"Helvetica Neue",
UIFontDescriptorFaceAttribute: @"Light"
}
];
From the docs:
Font Traits Dictionary Keys
The following constants can be used as keys to retrieve information about a font descriptor from its trait dictionary.
NSString *const UIFontSymbolicTrait; NSString *const UIFontWeightTrait; NSString *const UIFontWidthTrait; NSString *const UIFontSlantTrait;
This reads to me like these keys are designed only for getting information from a font descriptor—not for setting it. For example you could do something like this:
UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
NSDictionary *traits = [font.fontDescriptor objectForKey:UIFontDescriptorTraitsAttribute];
CGFloat weight = [traits[UIFontWeightTrait] floatValue];
Which would show you that the font you got back is a little bit heavier than the normal weight. This doesn't seem nearly as useful as being able to ask for a lighter weight of a font without having to give an exact name—but it seems to be the intended usage.
When looking for a bold or italic font, symbolic traits at least do appear to be respected. So this works nicely:
+ (UIFont*)fontWithFamily:(NSString*)family bold:(BOOL)bold italic:(BOOL)italic size:(CGFloat)pointSize {
UIFontDescriptorSymbolicTraits traits = 0;
if (bold) traits |= UIFontDescriptorTraitBold;
if (italic) traits |= UIFontDescriptorTraitItalic;
UIFontDescriptor* fd = [UIFontDescriptor
fontDescriptorWithFontAttributes:@{UIFontDescriptorFamilyAttribute: family,
UIFontDescriptorTraitsAttribute: @{UIFontSymbolicTrait:
[NSNumber numberWithInteger:traits]}}];
NSArray* matches = [fd matchingFontDescriptorsWithMandatoryKeys:
[NSSet setWithObjects:UIFontDescriptorFamilyAttribute, UIFontDescriptorTraitsAttribute, nil]];
if (matches.count == 0) return nil;
return [UIFont fontWithDescriptor:matches[0] size:pointSize];
}
e.g. [MyClass fontWithFamily:@"Avenir Next Condensed" bold:YES italic:NO size:12.0f];
I don't think this helps the OP, who was looking specifically for a light font with UIFontWeightTrait
, but it may help others with similar problems.