Skip to content

Instantly share code, notes, and snippets.

@ikonst
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikonst/9adc3663b472aa84abb2 to your computer and use it in GitHub Desktop.
Save ikonst/9adc3663b472aa84abb2 to your computer and use it in GitHub Desktop.
Enables creating a UIFont that's a variant of another font in a different family
@import Foundation;
@interface NSMutableAttributedString (FontWithFamily)
// Modifies the attributed text to change the font family while keeping
// font size and traits.
- (void)setFontFamily:(NSString *)fontFamily inRange:(NSRange)range;
- (void)setFontFamily:(NSString *)fontFamily;
@end
#import "NSMutableAttributedString+FontWithFamily.h"
#import "UIFont+FontWithFamily.h"
@implementation NSMutableAttributedString (FontWithFamily)
- (void)setFontFamily:(NSString *)fontFamily inRange:(NSRange)range {
[self enumerateAttribute:NSFontAttributeName inRange:range options:0 usingBlock:^(id value, NSRange blockRange, BOOL *stop) {
*stop = NO;
UIFont *oldFont = value;
UIFont *newFont = [oldFont fontWithFamily:fontFamily];
[self addAttribute:NSFontAttributeName value:newFont range:blockRange];
}];
}
- (void)setFontFamily:(NSString *)fontFamily {
[self setFontFamily:fontFamily inRange:NSMakeRange(0, self.length)];
}
@end
@import UIKit;
@interface UIFont (FontWithFamily)
// Gets a font from a different family while preserving point size
// and traits such as Bold and Italic.
- (UIFont *)fontWithFamily:(NSString *)fontFamily;
@end
#import "UIFont+FontWithFamily.h"
@implementation UIFont (FontWithFamily)
- (UIFont *)fontWithFamily:(NSString *)fontFamily {
UIFontDescriptor *desc = [self fontDescriptor];
//
// Change the family
//
UIFontDescriptor *newDesc = [desc fontDescriptorWithFamily:fontFamily];
//
// Preserve the traits (bold, italic)
//
// In symbolic traits, the lower 16 bits represent the typeface, and the upper 16 bits describe appearance of the font.
// We're interested in preserving typeface (TraitBold, TraitItalic, etc.)
// and NOT interested in preserving appearance (ClassSansSerif etc.)
//
// For example, when changing from Times to Helvetica, you cannot remove the ClassModernSerifs
// trait from the Times' description, nor add the ClassSansSerif trait to the Helvetica description.
// What you CAN do, is apply masked traits AFTER changing the font family.
//
newDesc = [newDesc fontDescriptorWithSymbolicTraits:(desc.symbolicTraits & 0xFFFF)];
//
// Preserve font point size.
//
return [UIFont fontWithDescriptor:newDesc size:self.pointSize];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment