Last active
June 24, 2017 03:48
-
-
Save ozouai/3851c7f4be2c6a4f02be to your computer and use it in GitHub Desktop.
Turns HTML into an attributed string with a custom font and paragraph spacing
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
// Omar Zouai | https://omarzouai.com/ | |
- (NSMutableAttributedString*)htmlToAttributed:(NSString*)html font:(UIFont*)font paragraphSpacing:(CGFloat)pSpacing { | |
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)} documentAttributes:nil error:nil]; | |
[string beginEditing]; | |
NSMutableParagraphStyle *pStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy]; | |
[pStyle setParagraphSpacing:pSpacing]; | |
[string enumerateAttributesInRange:NSMakeRange(0, string.length) options:nil usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) { | |
UIFont *theFont = [attrs objectForKey:@"NSFont"]; | |
UIFontDescriptor *desc = theFont.fontDescriptor; | |
UIFontDescriptorSymbolicTraits descSym = desc.symbolicTraits; | |
BOOL isBold = (descSym & UIFontDescriptorTraitBold) != 0; | |
BOOL isItalic = (descSym & UIFontDescriptorTraitItalic) != 0; | |
UIFont *targetFont = font; | |
if(isBold && isItalic) { | |
UIFontDescriptor *fontD = [font.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic]; | |
targetFont = [UIFont fontWithDescriptor:fontD size:0]; | |
} else if(isBold) { | |
UIFontDescriptor *fontD = [font.fontDescriptor fontDescriptorWithSymbolicTraits: UIFontDescriptorTraitItalic]; | |
targetFont = [UIFont fontWithDescriptor:fontD size:0]; | |
} else if(isItalic) { | |
UIFontDescriptor *fontD = [font.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold ]; | |
targetFont = [UIFont fontWithDescriptor:fontD size:0]; | |
} | |
[string addAttribute:NSFontAttributeName value:targetFont range:range]; | |
}]; | |
[string addAttribute:NSParagraphStyleAttributeName value:pStyle range:NSMakeRange(0, string.length)]; | |
[string endEditing]; | |
return string; | |
} |
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
NSString *htmlString = @"Hello <b>World</b>"; | |
NSFont *myFont = [UIFont fontWithName:@"Arial" size:14.0f]; | |
NSAttributedMutableString *string = [self htmlToAttributed:htmlString font:myFont paragraphSpacing:15.0f]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment