Last active
October 24, 2017 14:29
-
-
Save funkydevil/aff16a6c94dff283960b to your computer and use it in GitHub Desktop.
Chage font in attributed string, but save styles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
#import <UIKit/UIKit.h> | |
@interface NSMutableAttributedString (setFontButSaveStyle) | |
- (void)setFontButSaveStyle:(UIFont *)font; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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