我遇到了UIWebView的问题。我想在UIWebView中呈现我自己的html代码。
如果我使用下面的代码,它工作正常。
NSBundle *thisBundle = [NSBundle mainBundle];
NSString *path = [thisBundle pathForResource:@"foo" ofType:@"html"];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[self.webView loadHTMLString:@"foo.html" baseURL:baseURL];
我想用下面的代码渲染html。但它不起作用。 foo.html包含与NSString * one完全相同的内容。任何提示?提前致谢。 =)
NSString* one = @"<html><head><title></title></head><body><img src=\"image.jpg\"/></body></html>";
[self.webView loadHTMLString:one baseURL:nil] ;
答案 0 :(得分:23)
我使用的代码完美无缺:
NSString* htmlContent = @"<html><head><title></title></head><body><img src='image.jpg' /></body></html>";
[self.webView loadHTMLString:htmlContent baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
确保image.jpg包含在您的项目中。
答案 1 :(得分:1)
创建JS文件 demo.js 并添加代码
var hello = function(str){
return str;
};
添加UIWebView =&gt;将JavaScript嵌入到伪html文件中并将其加载到UIWebView
中 [self.webView loadHTMLString:@"<script src=\"demo.js\"></script>"
baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];
以下是进行JS调用的代码
NString *str=@"hi JavaScript";
NSString *function = [[NSString alloc] initWithFormat: @"hello(%@)", str];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:function];
现在,有一个重要的安全提示可以使其真正起作用:UIWebView实际上必须加载一个视图。它不必是可见的,但为了让WebKit引擎执行JS,它必须在视图上。