ArticalDetailCell.m
//
// ArticalDetailCell.m
// BlockChainNews
//
// Created by zsm on 2018/5/30.
// Copyright © 2018年 XinHuoKeJi. All rights reserved.
//
#import "ArticalDetailCell.h"
@interface ArticalDetailCell()<WKUIDelegate,WKNavigationDelegate>
@property (weak, nonatomic) IBOutlet UILabel *titileLab;
@property (weak, nonatomic) IBOutlet UILabel *timeLab;
@end
@implementation ArticalDetailCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
self.selectionStyle = UITableViewCellSelectionStyleNone;
self.myWebView.backgroundColor = [UIColor clearColor];
self.myWebView.scrollView.scrollEnabled = NO;
[self.myWebView setUserInteractionEnabled:NO];//是否支持交互
[self.myWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
self.myWebView.navigationDelegate = self;
self.myWebView.UIDelegate = self;
}
#pragma mark - WKNavigationDelegate
/* 页面开始加载 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
// [SVProgressHUD show];
}
/* 开始返回内容 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
}
/* 页面加载完成 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
[SVProgressHUD dismiss];
if (webView.isLoading) {
return;
}
__block CGFloat webViewHeight=0;
//获取内容实际高度(像素)@"document.getElementById(\"content\").offsetHeight;"
[webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
// 此处js字符串采用scrollHeight而不是offsetHeight是因为后者并获取不到高度,看参考资料说是对于加载html字符串的情况下使用后者可以,但如果是和我一样直接加载原站内容使用前者更合适
//获取页面高度,并重置webview的frame
webViewHeight = [result floatValue];
NSLog(@"%f",webViewHeight);
if (self.webViewHeightChanged) {
self.webViewHeightChanged(webViewHeight);
}
}];
// [webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable clientheight_str, NSError * _Nullable error) {
// float clientheight = [clientheight_str floatValue];
// webView.frame = CGRectMake(15, 10, kScreenWidth - 30, clientheight);
//
// [webView evaluateJavaScript:@"" completionHandler:^(id _Nullable, NSError * _Nullable error) {
//
// }];
// }];
// NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
// float clientheight = [clientheight_str floatValue];
// //设置到WebView上
// webView.frame = CGRectMake(15, 10, kScreenWidth - 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, 10, kScreenWidth - 30, height);
//
// //下面这两行是去掉不必要的webview效果的(选中,放大镜)
// [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
//
// [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
}
/* 页面加载失败 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
[[UIApplication sharedApplication].delegate.window makeToast:@"页面加载失败" duration:1.0 position:CSToastPositionCenter];
[SVProgressHUD dismiss];
}
/* 在发送请求之前,决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
//允许跳转
decisionHandler(WKNavigationActionPolicyAllow);
//不允许跳转
//decisionHandler(WKNavigationActionPolicyCancel);
}
/* 在收到响应后,决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
NSLog(@"%@",navigationResponse.response.URL.absoluteString);
//允许跳转
decisionHandler(WKNavigationResponsePolicyAllow);
//不允许跳转
//decisionHandler(WKNavigationResponsePolicyCancel);
}
//监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"contentSize"]) {
CGSize fitSize = [_myWebView sizeThatFits:CGSizeZero];
// NSLog(@"webview fitSize:%@",NSStringFromCGSize(fitSize));
CGRect rect = self.myWebView.frame;
rect.size.width = fitSize.width;
rect.size.height = fitSize.height;
self.myWebView.frame = rect;
}
}
- (void)setModel:(TypeDetailModel *)model{
self.titileLab.text = model.title;
self.timeLab.text = [NSString stringWithFormat:@"发布日期:%@",[ToolUtil getTimeWithStamp:model.update_time]];
NSString *result = [NSString stringWithFormat:@"<%@ %@",@"img",@"style='display: block; max-width: 100%;'"];
NSString*contentStr = model.content;
contentStr = [contentStr stringByReplacingOccurrencesOfString:@"<img" withString:result];
NSString *htmlStr = [NSString stringWithFormat:@"<html><head><meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\'/><meta content=\'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;\' name=\'viewport\' /><meta name=\'apple-mobile-web-app-capable\' content=\'yes\'><meta name=\'apple-mobile-web-app-status-bar-style\' content=\'black\'><link rel=\'stylesheet\' type=\'text/css\' /><style type=\'text/css\'> .color{color:#576b95;}</style></head><body><div id=\'content\'>%@</div>", contentStr];
//修改图片大小
NSString *re_imgSize = [NSString stringWithFormat:@"<head><style>img{width:%f !important;height:auto}</style></head>",kScreenWidth - 60];
NSString *htmlcontent = [NSString stringWithFormat:@"<head><style>img{max-width:%fpx !important;}</style></head><div id=\"webview_content_wrapper\">%@</div>%@",kScreenWidth-30,htmlStr,re_imgSize];
[self.myWebView loadHTMLString:htmlcontent baseURL:nil];
}
//-(void)layoutSubviews
//{
// [super layoutSubviews];
//}
//这里别忘了在dealloc理移除监听
- (void)dealloc {
NSLog(@"webView ---------dealloc");
[self.myWebView.scrollView removeObserver:self
forKeyPath:@"contentSize" context:nil];
}
@end
ArticalDetailCell.h
//
// ArticalDetailCell.h
// BlockChainNews
//
// Created by zsm on 2018/5/30.
// Copyright © 2018年 XinHuoKeJi. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TypeDetailModel.h"
#import "UIWebView+isLoading.h"
#import "MyWK.h"
typedef void(^WebViewHeightChangedBlock)(float height);
@interface ArticalDetailCell : UITableViewCell<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet MyWK *myWebView;
//@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (nonatomic, strong) TypeDetailModel *model;
@property (nonatomic, strong) WebViewHeightChangedBlock webViewHeightChanged;
@end
视图控制器中使用
//MARK:-- 适配iOS10 加载wkwebview 底部留白 计算高度不准确
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (self.tableView == scrollView) {
for (UIView *cell in self.tableView.visibleCells) {
if ([cell isKindOfClass:[ArticalDetailCell class]]) {
[((ArticalDetailCell *)cell).myWebView setNeedsLayout];
}
}
}
}
cellForRow中使用
ArticalDetailCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseid forIndexPath:indexPath];
if (self.model) {
[cell setModel:self.model];
cell.webViewHeightChanged = ^(float height){
//MARK:--计算webview高度
BOOL needReload = NO;
if(self.webViewHeight == 0 ) needReload=YES;
self.webViewHeight = height + 30;
if (needReload) {
// needReload = NO;
[self.tableView reloadData];
DLog(@"callback --------webViewheight %d",height);
}
};
}
return cell;