3

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?

Andrew Brown
  • 73
  • 2
  • 5
  • You're setting them after the dom and the page have already loaded. Should the act of setting them automatically cause them to be applied to the already loaded page? – Gruntcakes Jun 01 '12 at 16:39
  • Yes, I think setting these properties after page load should work. Or, more accurately, I don't know of any reason why it wouldn't work and I have confirmed it does work on Chrome and Safari. – Andrew Brown Jun 02 '12 at 03:31

1 Answers1

1

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.

Andrew Brown
  • 73
  • 2
  • 5