2013-02-14 68 views
0

在我的應用程序中,我必須從網上加載的webPage更改字體。如何在iOS中的UIWebView的文檔目錄中使用Javascript?

首先,我將我的CustomJava.js文件存儲在在線託管中,並使用該文件更改iOS應用中的字體。

這是我的一些代碼。

- (void)webViewDidFinishLoad:(UIWebView *)webView 
{ 
    NSString *js = [NSString stringWithFormat:@"var script = document.createElement('script');" 
        "script.type = 'text/javascript';" 
    "script.src = 'http://www.gustohei.com/SYjs/customJava.js';"]; 

    js = [NSString stringWithFormat:@"%@ document.getElementsByTagName('head')[0].appendChild(script);", js]; 
    [self.webViewOfBrowser stringByEvaluatingJavaScriptFromString:js]; 

    UIApplication *app = [UIApplication sharedApplication]; 
    app.networkActivityIndicatorVisible = NO; 
} 

這很好,正確地更改字體。

在我的情況下,我想保留在我的文檔目錄中的JS文件,並希望從文檔目錄中使用該文件。我不想從網上使用。

所以我寫了下面的代碼。

- (void)webViewDidFinishLoad:(UIWebView *)webView 
{ 
    NSString *jsPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"customJava.js"]; 

    NSString *js = [NSString stringWithFormat:@"var script = document.createElement('script');" 
        "script.type = 'text/javascript';" 
        "script.src ='%@'",jsPath]; 

    js = [NSString stringWithFormat:@"%@ document.getElementsByTagName('head')[0].appendChild(script);", js]; 
    [self.webViewOfBrowser stringByEvaluatingJavaScriptFromString:js]; 

    UIApplication *app = [UIApplication sharedApplication]; 
    app.networkActivityIndicatorVisible = NO; 
} 

但是這是行不通的。 如何做到這一點?

回答

1
  1. 在Xcode的項目導航器(左欄)中點擊藍色的項目圖標。
  2. 在主窗口
  3. 打開「編譯源」節
  4. 找到你的Javascript文件在列表中刪除選擇「構建階段」選項卡。
  5. 「複製包資源」部分
  6. 加入你的Javascript文件添加到列表
  7. 打開

使用然後加載JS文件下面的代碼

[[NSBundle mainBundle] pathForResource:@"script.js" ofType:nil]; 

UPDATE: 的Xcode 4.5現在創建一個當您只是將JavaScript文件添加到項目而不從「編譯源」部分刪除它時發出警告:

警告:沒有規則來處理文件「FILEPATH」式的 sourcecode.javascript用於建築的ARMv7

+0

這不是工作兄弟。我像你說的那樣將相同的JS文件加載到Bundle中。但字體不會像當我使用來自Online的JS文件時那樣改變。 – 2013-02-14 08:12:42

+0

此鏈接可能會幫助你然後http://stackoverflow.com/questions/5733883/loading-javascript-into-a-uiwebview-from-resources – iphonic 2013-02-14 08:13:52

0

保持javascript文件,並在文件目錄同一文件夾中的HTML和Just包括你的HTML的JavaScript裝載在網頁視圖

<script src = "CustomJava.js" type="application/javascript"></script> 

,然後調用javascript函數在你的代碼是這樣的:(例如「changeFont();」是你要調用在網頁視圖函數的名稱)

NSString *javascriptFunctionCall = [NSString stringWithFormat:@"changeFont('%@');",self.fontSize]; 

    [bookWebView stringByEvaluatingJavaScriptFromString:javascriptFunctionCall]; 
+0

我不明白你的意思是兄弟?我正在從網頁加載頁面,並希望將js代碼插入UIWebView中從網頁加載的頁面。 – 2013-02-14 08:39:40

+0

我正在加載網頁,如網頁瀏覽器,並希望將我的JS代碼添加到UIWebView中加載的頁面。 – 2013-02-14 08:41:07

+0

好吧你不能編輯網頁從網頁?它沒有託管在你的服務器上? – Bhupendra 2013-02-14 08:41:11

相關問題