创建webview
@property (strong, nonatomic) UIWebView *webView;
- (UIWebView *)webView
{
if (_webView) {
return _webView;
}
_webView = [[UIWebView alloc] initWithFrame:self.bounds];
_webView.scrollView.showsVerticalScrollIndicator = NO;
_webView.backgroundColor = [UIColor clearColor];
_webView.scrollView.userInteractionEnabled = YES;
_webView.scrollView.bounces = NO;
_webView.delegate = self;
[_webView sizeToFit];
// 设置webview 的背景图片
_webView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backgroundcolor"]];
_webView.opaque = NO;
return _webView;
}
展示文本内容
- (void)addWebViewWith:(NSString *)content
{
NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@</div>", content];
[self.webView loadHTMLString:htmlcontent baseURL:nil];
[self addSubview:self.webView];
}
设置webview内容可滑动性,并自适应高
在webViewDidFinishLoad
方法里
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//获取页面高度(像素)
NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
float clientheight = [clientheight_str floatValue];
//设置到WebView上
CGRect myFrame = CGRectMake(CGRectGetMinX(webView.frame), CGRectGetMinY(webView.frame), CGRectGetWidth(webView.frame), clientheight);
//获取WebView最佳尺寸(点)
CGSize frame = [webView sizeThatFits:myFrame.size];
//获取内容实际高度(像素)
NSString * height_str= [webView stringByEvaluatingJavaScriptFromString: @"document.getElementById('webview_content_wrapper').offsetHeight + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-top')) + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-bottom'))"];
float height = [height_str floatValue];
//内容实际高度(像素)* 点和像素的比
height = height * frame.height / clientheight;
//再次设置WebView高度(点)
webView.scrollView.contentSize = CGSizeMake(0, height);
/*
如果需要修改webview文本样式或背景色,可以在这里设置
**/
// 设置背景色
// [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#FFDAB9'"];
//字体大小
//[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '330%'"];
//字体颜色
//[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'gray'"];
}