Skip to content

Instantly share code, notes, and snippets.

@karlwhite
Last active March 15, 2016 14:03
Show Gist options
  • Save karlwhite/e1c4922f2e9d7fb61d99 to your computer and use it in GitHub Desktop.
Save karlwhite/e1c4922f2e9d7fb61d99 to your computer and use it in GitHub Desktop.
// 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