iOS开发, 使用web加载html数据
[_webView loadHTMLString:_contentString baseURL:nil];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
/*设置cell的内容 */
if (!_webView){
_webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
_webView.height = 20;
_webView.delegate = self;
_webView.scrollView.scrollEnabled = NO;
[cell.contentView addSubview:_webView];
}
/*忽略点击效果 */
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
return cell;
}
/**
* 设置cell高度
*/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
/*通过webview代理获取到内容高度后,将内容高度设置为cell的高 */
return _webView.frame.size.height;
}
/**
* webView完成加载
*/
-(void)webViewDidFinishLoad:(UIWebView *)webView{
NSString * str = [NSString stringWithFormat:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth = %f;" // UIWebView中显示的图片宽度
"for(i=0;i <document.images.length;i++){"
"myimg = document.images[i];"
"if(myimg.width > maxwidth){"
"oldwidth = myimg.width;"
"myimg.width = maxwidth;"
"}"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);",SCREEN_WIDTH - 20];
[webView stringByEvaluatingJavaScriptFromString:str];
[webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
// UIScrollView *webViewScroll = webView.subviews[0];//取到webView的Scrollview
NSInteger height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] intValue];
webView.frame = CGRectMake(webView.frame.origin.x, webView.frame.origin.y, SCREEN_WIDTH,height);
[self.tableView reloadData];
_webView.scrollView.bounces=NO; //控制webView滚动时, 不超过边界
//加载完成后重新设置 tableview的cell的高度,和webview的frame
}