Last active
March 15, 2016 14:03
-
-
Save karlwhite/e1c4922f2e9d7fb61d99 to your computer and use it in GitHub Desktop.
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
// Tweak background styling | |
UIColor *backgroundColor = [UIColor whiteColor]; | |
HTMLDocument *document = [HTMLDocument documentWithString:htmlString]; | |
htmlString = [[document rootElement] serializedFragment]; | |
// Fetch the body tag to look for inline background styles | |
HTMLElement *body = [document firstNodeMatchingSelector:@"body"]; | |
if ( [body attributes] && [[body attributes] count] ) { | |
Boolean foundColor = NO; | |
// Find either an inline CSS style attribute, or an HTML bgcolor attribute | |
NSString *styles = [[body attributes] objectForKey:@"style"]; | |
NSString *bgcolor = [[body attributes] objectForKey:@"bgcolor"]; | |
if ( !foundColor && styles && [styles length] ) { | |
NSArray *keyValueList = [styles componentsSeparatedByString:@";"]; | |
// Iterate through each css style to find a background color | |
for (NSString *item in keyValueList) { | |
if ( [item containsString:@"background"] && [item containsString:@"#"] ) { | |
NSRange range = [item rangeOfString:@"#"]; | |
backgroundColor = [UIColor colorWithHexString:[item substringFromIndex:range.location+1]]; | |
foundColor = YES; | |
} | |
} | |
} | |
// If no CSS color exists, try the HTML bgcolor attribute instead | |
if ( !foundColor && bgcolor && [bgcolor length] ) { | |
backgroundColor = [UIColor colorWithHexString:[bgcolor substringFromIndex:1]]; | |
foundColor = YES; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment