Gal*_*Gal 3 iphone uiwebview ios
我正在尝试将本地css文件"注入"到下载的xhtml文件中.
我找到了许多如何做的例子,但它对我不起作用......
这是我的代码:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *cssPath = [path stringByAppendingPathComponent:@"test.css"];
NSString *js = [NSString stringWithFormat:@"var cssNode = document.createElement('link');"
"cssNode.type = 'text/css';"
"cssNode.rel = 'stylesheet';"
"cssNode.href = '%@';", cssPath];
js = [NSString stringWithFormat:@"%@document.getElementsByTagName('head')[0].appendChild(cssNode);", js];
//m_webview is a member
[m_webView stringByEvaluatingJavaScriptFromString:js];
}
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?
谢谢,
我也很难做到这一点.
我试图从服务器加载HTML文件并使用本地CSS文件更改样式.
起初我用过
[webView loadRequest:reqObj];
Run Code Online (Sandbox Code Playgroud)
当它击中时,- (void)webViewDidFinishLoad:(UIWebView *)webView我试图将CSS文件作为一个孩子推向'头':
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *cssPath = [path stringByAppendingPathComponent:@"style.css"];
NSString *js = [NSString stringWithFormat:@"var cssChild = document.createElement('link');"
"cssChild = 'text/css';"
"cssChild = 'stylesheet';"
"cssChild = '%@';", cssPath];
js = [NSString stringWithFormat:@"%@ document.getElementsByTagName('head')[0].appendChild(cssChild);", js];
[webView stringByEvaluatingJavaScriptFromString:js];
}
Run Code Online (Sandbox Code Playgroud)
所以......它不起作用......
然后我试过了
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
Run Code Online (Sandbox Code Playgroud)
(我将HTML字符串复制到htmlString中)然后,在内部- (void)webViewDidFinishLoad:(UIWebView *)webView我按照上面的代码注入了CSS.它奏效了!
但是......我的HTML文件存储在远程服务器中,我没有HTML字符串,所以我使用了
NSString* myFile = [NSString stringWithFormat:@"http://blablabla.com/file.html"];
NSString* myFileURLString = [myFile stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSData *myFileData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myFileURLString]];
NSString* myFileHtml = [[[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding] autorelease];
Run Code Online (Sandbox Code Playgroud)
获取HTML.现在,我在'myFileHtml'中有原始的HTML文本.我现在用
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:myFileHtml baseURL:baseURL];
Run Code Online (Sandbox Code Playgroud)
并在'webViewDidFinishLoad'中捕获响应,将我的CSS文件注入其中并且工作正常:)
也许这个问题有另一个更优雅的解决方案,但这就是我提出来的......
希望它有所帮助.