Why doesn’t UIWebView reflow text after column width and gap are set via javascript?

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?

Problem courtesy of: Andrew Brown


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.

Solution courtesy of: Andrew Brown

稿源:CSS3 Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Why doesn’t UIWebView reflow text after column width and gap are set via javascript?

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录