Skip to content

Instantly share code, notes, and snippets.

@funkydevil
Last active October 24, 2017 14:29
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 funkydevil/aff16a6c94dff283960b to your computer and use it in GitHub Desktop.
Save funkydevil/aff16a6c94dff283960b to your computer and use it in GitHub Desktop.
Chage font in attributed string, but save styles
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface NSMutableAttributedString (setFontButSaveStyle)
- (void)setFontButSaveStyle:(UIFont *)font;
@end
#import "NSMutableAttributedString+setFontButSaveStyle.h"
@implementation NSMutableAttributedString (setFontButSaveStyle)
-(void)setFontButSaveStyle:(UIFont *)font
{
[self enumerateAttributesInRange:NSMakeRange(0, self.length)
options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
usingBlock:^(NSDictionary *attributes, NSRange range, BOOL *stop)
{
NSMutableDictionary *newAttributes = [attributes mutableCopy];
//Do changes
if ([newAttributes objectForKey:NSFontAttributeName])
{
UIFont *currentFont = (UIFont *)[attributes objectForKey:NSFontAttributeName];
UIFontDescriptorSymbolicTraits currntSymbolicTraits = currentFont.fontDescriptor.symbolicTraits;
UIFont *newFont = font;
UIFontDescriptor *newFontDescriptior = [newFont.fontDescriptor fontDescriptorWithSymbolicTraits:currntSymbolicTraits];
newFont = [UIFont fontWithDescriptor:newFontDescriptior size:newFont.fontDescriptor.pointSize];
[newAttributes setValue:newFont forKey:NSFontAttributeName];
}
[self addAttributes:newAttributes range:range]; //Apply effects
}];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment