I am loading an html file into a UIWebView and setting the "-webkit-column-width" and "-webkit-column-gap" style property via javascript in webViewDidFinishLoad, but the text isn't reflowing into columns.
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *urlForView = [self.book.chapterURLs objectAtIndex:0];
self.webView.delegate = self;
self.webView.scrollView.bounces = NO;
self.webView.scrollView.pagingEnabled = YES;
[self.webView loadRequest:[NSURLRequest requestWithURL:urlForView]];
}
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
NSString *jsString = @"document.getElementsByTagName('body')[0]. setAttribute('style','-webkit-column-width: 733px; -webkit-column-gap: 20px;');)";
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
}
I've confirmed via alerts that the style attributes are being set correctly, so I don't understand why they are having no effect. Executing that same javascript string via the console in Safari has the desired affect. Any idea why this doesn't work in UIWebView?
I still don't understand why the code above doesn't work, but I was able to find a workaround by grabbing the external stylesheet for file via javascript, then editing that CSS file via javascript.
NSString *varMySheet = @"var mySheet = document.styleSheets[0];";
NSString *addCSSRule = @"function addCSSRule(selector, newRule) {"
"ruleIndex = mySheet.cssRules.length;"
"mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);" // For Firefox, Chrome, etc.
"}";
NSString *insertRule1 = [NSString stringWithFormat:@"addCSSRule('html', 'padding: 0px; height: %fpx; -webkit-column-gap: 0px; -webkit-column-width: %fpx;')", webView.frame.size.height, webView.frame.size.width];
NSString *insertRule2 = [NSString stringWithFormat:@"addCSSRule('p', 'text-align: justify;')"];
//NSString *setTextSizeRule = [NSString stringWithFormat:@"addCSSRule('body', '-webkit-text-size-adjust: %d%%;')", currentTextSize];
[webView stringByEvaluatingJavaScriptFromString:varMySheet];
[webView stringByEvaluatingJavaScriptFromString:addCSSRule];
[webView stringByEvaluatingJavaScriptFromString:insertRule1];
[webView stringByEvaluatingJavaScriptFromString:insertRule2];
Hat tip to the AePubReader project where I found this code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With