您的位置:首页 > 移动开发

iOS: UIWebview loadhtmlstring & Local css/js/image resources

2012-05-29 18:48 525 查看
UIWebView 既可以load by url,还可以load html string。即你可以自己generate html string来用web view显示。load html string 典型的应用是:url所对应的web page内容太多,如果只需要部分的html content,那么可以通过http request获取url的html content,然后只选取需要的部分,然后通过load html string来显示。

自己生成的html,有时无法避免要使用local css, js or image (当然你也可以使用url来链接到网上的css/js/image)。

假设在你的ios app里的resource folder里已经存放了a webpage.css and a test.js,那么你生成的html string应该这样include them

NSString* htmlHeader=@"<html><head><style type='text/css'>@import url('webpage.css');</style><script type='text/javascript' charset='utf-8'
src='test.js'></script></head><body>";
NSString* htmlBody=@"<p> <img alt=\"dept\" src=\"https://www6.cityu.edu.hk/sa/images/30May12.jpg\" /></p>";
NSString* htmlFooter=@"</body></html>";
NSString* strHtml=[[NSString
alloc] initWithFormat:@"%@%@%@",htmlHeader,htmlBody,htmlFooter];

[webView
loadHTMLString:strHtml
baseURL:[NSURL
fileURLWithPath: [[NSBundle
mainBundle] resourcePath]
isDirectory: YES
]];

注意:

1. baseURL就是你的resource folder path

2. 如果把<script type='text/javascript' charset='utf-8' src='test.js'></script>改成<script type='text/javascript' charset='utf-8' src='test.js' />则无法load js (ref
link: http://stackoverflow.com/questions/7840127/uiwebview-loadhtmlstring-not-working-in-ios5)
3. 当你在ios project里创建js或者把js添加进来后,by default .js文件默认会被当作代码被compiled (你在build project时就会看到warning),因此你需要将.js files从“compile sources” move to "Copy bundle resources",见下图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: