温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在iOS中计算WebView的高度

发布时间:2021-04-08 17:04:49 来源:亿速云 阅读:330 作者:Leah 栏目:移动开发

本篇文章为大家展示了怎么在iOS中计算WebView的高度,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

获取最新的内容高度赋给webView:

//添加监听
[_WebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"WejinWuLiuViewController"];
//监听回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
 
 if ([keyPath isEqualToString:@"contentSize"]) {
 
 _webViewHeight = [_WebView.scrollView contentSize].height;
 CGRect newFrame = _WebView.frame;
 newFrame.size.height = _webViewHeight;
 _WebView.frame = newFrame;
 }
}

iOS开发之解决WebView自适应内容高度

首先如果直接进行内容展示,或者进行sizeToFit的操作,那么可能会造成图片超过屏幕大小,字体变得很小的结果,所以这里用到了UIWebView的delegate方法和添加了html的标签语言,使用了javascript操作方法。具体可以研究代码,如下:

//web 
-(UIWebView *)detailWebView 
{ 
if (_detailWebView == nil) { 
_detailWebView = [UIWebView new]; 
_detailWebView.delegate = self; 
_detailWebView.scrollView.bounces = NO; 
_detailWebView.scrollView.showsHorizontalScrollIndicator = NO; 
_detailWebView.scrollView.scrollEnabled = NO; 
_detailWebView.dataDetectorTypes = UIDataDetectorTypeAll; 
[_detailWebView sizeToFit]; 
} 
return _detailWebView; 
}
NSString *htmlcontent = [NSString stringWithFormat:@"<head><style>img{max-width:%fpx !important;}</style></head><div id=\"webview_content_wrapper\">%@</div>",f_Device_w-30,detailDic[@"content"]]; 

[_detailWebView loadHTMLString:htmlcontent baseURL:nil];
#pragma mark ----- webView 的 delegate 
- (void)webViewDidFinishLoad:(UIWebView *)webView 
{ 
//获取页面高度(像素) 
NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"]; 
float clientheight = [clientheight_str floatValue]; 
//设置到WebView上 
webView.frame = CGRectMake(15, _whereNewsLabel.bottom+10, f_Device_w-30, clientheight); 

//下面这样写就是获取到比较准确的内容高度,不需要再进行其他计算了 
//获取内容实际高度(像素) 
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]; 

//再次设置WebView高度(点) 
webView.frame = CGRectMake(15, _whereNewsLabel.bottom+10, f_Device_w-30, height); 

if ([self.delegate respondsToSelector:@selector(backWebViewWithHeight:)]) { 
[self.delegate backWebViewWithHeight:webView.bottom+5]; 
} 
}

上述内容就是怎么在iOS中计算WebView的高度,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI