cell加載html文本(計算UIWebView、WKWebView高度)

.h文件

    //
    //  XBWCSGoodsDetailContentInfoCell.h
    //  wcs
    //
    //  Created by 劉飛 on 2018/8/2.
    //  Copyright © 2018年 ahxb. All rights reserved.
    //

    #import <UIKit/UIKit.h>

    typedef void (^ReloadBlock)(void);
    @interface XBWCSGoodsDetailContentInfoCell : UITableViewCell

    @property(nonatomic,copy)NSString *htmlString;
    @property(nonatomic,copy)ReloadBlock reloadBlock;
    +(CGFloat)cellHeight;

    @end

.m文件

//
//  XBWCSGoodsDetailContentInfoCell.m
//  wcs
//
//  Created by 劉飛 on 2018/8/2.
//  Copyright © 2018年 ahxb. All rights reserved.
//  商品詳情詳情內容區域cell

#import "XBWCSGoodsDetailContentInfoCell.h"
#import <WebKit/WebKit.h>

@interface XBWCSGoodsDetailContentInfoCell()<UIWebViewDelegate,UIWebViewDelegate>//WKUIDelegate,WKNavigationDelegate>

@property (nonatomic,strong)UIWebView *webview;
@end

static CGFloat staticheight = 0;
@implementation XBWCSGoodsDetailContentInfoCell


+(CGFloat)cellHeight
{
    return staticheight;
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    [self.contentView addSubview:self.webview];
}
return self;
}


 -(void)setHtmlString:(NSString *)htmlString
{
_htmlString = htmlString;

if (isEmptyStr(_htmlString)) {
    staticheight = 0;
    if (_reloadBlock) {
        _reloadBlock();
    }
}else{
    [self.webview loadHTMLString:[self reSizeImageWithHTML:_htmlString] baseURL:nil];
}

}
 -(void)webViewDidFinishLoad:(UIWebView *)webView
{
CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
self.webview.frame = CGRectMake(0, 0, SCREEN_WIDTH, height);
self.webview.hidden = NO;
if (staticheight != height+1) {
    staticheight = height+1;
    if (staticheight > 0) {
        if (_reloadBlock) {
            _reloadBlock();
        }
    }
}
}
-(UIWebView *)webview
{
if (!_webview) {
    _webview =[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];//這裏一定要寫1,不然高度不準確
    _webview.userInteractionEnabled = NO;
    _webview.hidden = YES;
    _webview.delegate = self;
}
return _webview;
}



/*
 *  讓html文本適應屏幕
 */
-(nullable NSString *)reSizeImageWithHTML:(NSString *)html {
return [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><style type='text/css'>img{width:%fpx}</style>%@", SCREEN_WIDTH-SIZE(15), html];//-SIZE(15)是爲了html文本距離右邊一定的間距,不然太緊貼邊緣了
}



@end

上面是UIWebView加載html文本的方法,如果換成WKWebView將.m文件換成下面的

//
//  LFWKWebViewShowHtmlCell.m
//  CommonToolDemo
//
/ /  Created by 劉飛 on 2018/11/3.
//  Copyright © 2018年 ahxb. All rights reserved.
//

#import "XBWCSGoodsDetailContentInfoCell.h"
#import <WebKit/WebKit.h>

@interface XBWCSGoodsDetailContentInfoCell ()<WKUIDelegate,WKNavigationDelegate>
@property(nonatomic,strong)WKWebView * wkWebView;
@end

static CGFloat staticheight = 0;
@implementation XBWCSGoodsDetailContentInfoCell
+(CGFloat)cellHeight
{
    return staticheight;
}
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:self.wkWebView];
}
return self;
}

-(WKWebView *)wkWebView{
if (!_wkWebView) {
    _wkWebView = [[WKWebView alloc] init];
    
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    wkWebConfig.userContentController = wkUController;
    wkWebConfig.userContentController = wkUController;
    _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 1) configuration:wkWebConfig];
    _wkWebView.navigationDelegate = self;
    _wkWebView.userInteractionEnabled = NO;
    _wkWebView.UIDelegate = self;
    _wkWebView.scrollView.scrollEnabled = NO;
}
return _wkWebView;
}
-(void)setHtmlString:(NSString *)htmlString{
_htmlString = htmlString;
NSString *jSString =  [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><style type='text/css'>img{width:%fpx}</style>%@", [UIScreen mainScreen].bounds.size.width-15, _htmlString];
[self.wkWebView loadHTMLString:jSString baseURL:nil];
}
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{

}

// 頁面加載完成之後調用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
__weak typeof(self)bself = self;
[webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id data, NSError * _Nullable error) {
    CGFloat height = [data floatValue];
    //ps:在WKWebView中前者offsetHeight獲取自己加載的html片段,高度獲取是相對準確的,但是若是加載的是原網站內容,用這個獲取,會不準確,改用document.body.scrollHeight之後就可以正常顯示,這個情況是我嘗試了很多次方法才正常顯示的
    CGRect webFrame = webView.frame;
    webFrame.size.height = height;
    webView.frame = webFrame;
    if (staticheight != height+1) {
        staticheight = height+1;
        if (staticheight > 0) {
            if (bself.reloadBlock) {
               bself.reloadBlock();
            }
        }
    }
}];


}
@end

ViewController中設置cell的高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   return [XBWCSGoodsDetailContentInfoCell cellHeight];
}

ViewController中創建 cell

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(bself);
XBWCSGoodsDetailContentInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XBWCSGoodsDetailContentInfoCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.htmlString = isEmptyStr(self.goodsDetailModel.content)?@"":self.goodsDetailModel.content;
    cell.reloadBlock =^(void)
    {
        [bself.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    };
    return cell;
}

爲了加載的流暢度,建議還是用WKWebView,內存消耗上講也會比UIWebView好很多
Demo集合

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章