使用相对路径或文件:引用图像的路径不适用于 UIWebView。相反,您必须使用正确的 baseURL 将 HTML 加载到视图中:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
然后,您可以像这样引用您的图像:
<img src="myimage.png">
或者像这样在 CSS 中:
background-image: url(loading.gif)
例子 :
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bgfull.png"];
NSURL *url = [[NSURL alloc] initFileURLWithPath:path isDirectory:NO];
NSString *size = [@"100%25" stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *contentHtml = [NSString stringWithFormat:@"<html>\
<head>\
<style type=\"text/css\">\
html {height:%@;}\
body {height:%@; margin:0; padding:0; color:white; font-size:40px;}\
#bg {position:fixed; top:0; left:0; width:%@; height:%@;}\
#content {position:relative; z-index:1;}\
</style>\
</head>\
<body>\
<div id=\"bg\"><img src=\"%@\" width=\"%@\" height=\"%@\"></div>\
<div id=\"content\"><font color=\"#DAF899\" size=\"+4\"><b>%@</b></font><p>%@</p></div>\
</body>\
</html>", size, size, size, size, url, size, size, self.navigationItem.title, content];
[webView loadHTMLString:contentHtml baseURL:nil];