iPhone ePub Reader更改ePub中所有页面的字体,而不是当前的webview内容

时间:2013-07-03 03:39:22

标签: iphone ios webview

我正在开发iphone应用程序之类的iphone应用程序。我在XML解析epub文件后加载了UIWebView文件的内容。我更改了字体大小& UIWebView的字体系列。我想更改字体大小& ePub book中所有页面的字体系列。如何存储UIWebView的设置,以便将其应用于EPub书中的所有页面。 这是代码我如何改变weview的字体。

NSString *yourHTMLSourceCodeString = [App_delegate.webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];

[App_delegate.webView loadHTMLString:[NSString stringWithFormat:@"<div style=' font-family:Times New Roman;'>%@",yourHTMLSourceCodeString] baseURL:nil];

2 个答案:

答案 0 :(得分:2)

检查此项目https://github.com/fedefrappi/AePubReader。您可以在NSUserDefaults中存储fontName和fontSize值,并在webView委托方法webViewDidFinishLoad中添加CSS规则:

- (void)webViewDidFinishLoad:(UIWebView *)theWebView{

    NSString *fontName = [[NSUserDefault standartUserDefaults] objectForKey:@"fontName"];
    NSNumber *currentTextSize = [[NSUserDefault standartUserDefaults] objectForKey:@"currentTextSize"];

    NSString *varMySheet = @"var mySheet = document.styleSheets[0];";

    NSString *addCSSRule =  @"function addCSSRule(selector, newRule) {"
    "if (mySheet.addRule) {"
    "mySheet.addRule(selector, newRule);"                               // For Internet Explorer
    "} else {"
    "ruleIndex = mySheet.cssRules.length;"
    "mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);"   // For Firefox, Chrome, etc.
    "}"
    "}";


    NSString *setTextSizeRule = [NSString stringWithFormat:@"addCSSRule('body', '-webkit-text-size-adjust: %d%%;')", [currentTextSize floatValue]];
    NSString *setFont = [NSString stringWithFormat:@"addCSSRule('body', 'font-family:%@;')", fontName];


    [theWebView stringByEvaluatingJavaScriptFromString:varMySheet];

    [theWebView stringByEvaluatingJavaScriptFromString:addCSSRule];

    [theWebView stringByEvaluatingJavaScriptFromString:setTextSizeRule];

    [theWebView stringByEvaluatingJavaScriptFromString:setFont];
}

答案 1 :(得分:0)

虽然帖子太旧了,但上面的答案对我帮助很大,但我在 Swift 中这样做时遇到了问题。所以,这个答案可能会节省一些人的时间。

let varMySheet = "var mySheet = document.styleSheets[0];"

let addCSSRule = "function addCSSRule(selector, newRule) {if (mySheet.addRule) {mySheet.addRule(selector, newRule);} else { ruleIndex = mySheet.cssRules.length;mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);}}"

let setTextSizeRule = "addCSSRule('body', '-webkit-text-size-adjust: \(fontPercentage)%;')"


self.webView.stringByEvaluatingJavaScriptFromString(varMySheet)
self.webView.stringByEvaluatingJavaScriptFromString(addCSSRule)
self.webView.stringByEvaluatingJavaScriptFromString(setTextSizeRule)

fontPercentage 是我班级中的一个变量。默认值为100,您可以增加/减少该值。

只需更新fontSize,即使用“ -webkit-text-size-adjust ”属性。以下代码就足够了:

let textSizeRule = "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '\(fontPercentage)%'"
self.webView.stringByEvaluatingJavaScriptFromString(textSizeRule)