TableViewCell 中嵌入WKWebview 显示HTML字符串,TableView高度自适应

需求:每个tableviewcell 添加一个wkwebview 用于显示HTML 要求webview高度自适应,,每个cell高度自适应,,

网上查的资料,,使用的通知来刷新tableview,,会使tableview刷新次数过多,,本文的方法tableview只刷新一次

实现思路:cell中添加一个代理和一个index属性(cell协议方法中传入indexpath.row) 在webview加载完HTML协议方法中重新设置webview的高度 通过代理把每个cell的webview高度和这个cell的index传回Controller,在代理方法中把传回的index作为key,webview高度作为value存入一个字典,,当所有的cell里webview都加在完成,,此时Controller中已有一个保存了所有cell高度(即webview高度)的字典,,tableview设置高度的协议方法中通过indexpath.row 去字典中取cell的高度即可。。

怎样防止tableview刷新陷入死循环?通过存入本地一个状态,,具体看代码






为了方便在工程中添加名为test.text的文本文件,里面是一个数组,每个元素是字典存放HTML字符串

(

{

  option = "<p style=\"line-height:20.1pt; margin:5pt 0pt\"><span style=\"font-family:'Times New Roman'; font-size:10.5pt\">A.</span><span style=\"font-family:'Times New Roman'; font-size:10.5pt\"> </span><span style=\"color:#333333; font-family:'Times New Roman'; font-size:10.5pt\">0.643(</span><span style=\"color:#333333; font-family:\U5b8b\U4f53; font-size:10.5pt\">\U7cbe\U786e\U5230\U767e\U5206\U4f4d</span><span style=\"color:#333333; font-family:'Times New Roman'; font-size:10.5pt\">)</span></p>";

},

{

option = "<p style=\"line-height:20.1pt; margin:5pt 0pt\"><span style=\"font-family:'Times New Roman'; font-size:10.5pt\">B.</span><span style=\"font-family:'Times New Roman'; font-size:10.5pt\"> </span><span style=\"color:#333333; font-family:'Times New Roman'; font-size:10.5pt\">0.64(</span><span style=\"color:#333333; font-family:\U5b8b\U4f53; font-size:10.5pt\">\U7cbe\U786e\U5230\U767e\U5206\U4f4d</span><span style=\"color:#333333; font-family:'Times New Roman'; font-size:10.5pt\">)</span></p>";

}


Controller.m中


@interface SecondViewController ()<UITableViewDelegate,UITableViewDataSource,webViewCellDelegate>


@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) NSMutableDictionary *cellHDic;

@property (nonatomic, strong) NSMutableArray *dataArr;


@end


@implementation SecondViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    /// 存放所有cell里webview高度的字典

    self.cellHDic = [NSMutableDictionary dictionary];

    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];

    [self.view addSubview:self.tableview];

    self.tableview.delegate = self;

    self.tableview.dataSource = self;

    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;

    /// 防止tableview不停刷新的状态

    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"reload"];

    [self loadData];

}

- (void)loadData{

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    /// 从工程中取出数据

    NSBundle *mainBundle = [NSBundle mainBundle];

    NSString *txtPath = [mainBundle pathForResource:@"test" ofType:@"txt"];

    NSArray *arr = [NSArray arrayWithContentsOfFile:txtPath];

    self.dataArr = [NSMutableArray arrayWithArray:arr];

    [self.tableview reloadData];

    

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.dataArr.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld%ld", [indexPath section], [indexPath row]];

    SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {

        cell = [[SecondTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    cell.backgroundColor = [UIColor whiteColor];

    cell.delegate = self;

    NSDictionary *dic = self.dataArr[indexPath.row];

    [cell refreshWebView:dic[@"option"] indexPath:indexPath.row];

    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return [self.cellHDic[[NSString stringWithFormat:@"%ld",indexPath.row]] floatValue];

}

- (void)webViewDidFinishLoad:(CGFloat)webHeight cellIndex:(NSInteger)index{

    [self.cellHDic setValue:[NSString stringWithFormat:@"%f",webHeight] forKey:[NSString stringWithFormat:@"%ld",index]];

    /// 防止一直刷新  只有字典中的元素个数和tableviewcell个数相同时才刷新tableview

    if (self.cellHDic.count==self.dataArr.count) {

        /// 通过NSUserDefaults 存的一个状态让tableview只刷新一次

        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"reload"] isEqualToString:@"0"]) {

            NSArray *paths = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:index inSection:0],nil];

            [self.tableview reloadRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];

            [MBProgressHUD hideHUDForView:self.view animated:YES];

            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"reload"];

        }

    }

}


SecondTableViewCell.h


@protocol webViewCellDelegate<NSObject>

/// 传回webview高度的代理

- (void)webViewDidFinishLoad:(CGFloat)webHeight cellIndex:(NSInteger)index;


@end


@interface SecondTableViewCell : UITableViewCell


@property (nonatomic,weak) id<webViewCellDelegate>delegate;

@property (nonatomic, assign) NSInteger indexPath;

- (void)refreshWebView:(NSString *)url indexPath:(NSInteger)index;


@end


SecondTableViewCell.m

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

        [self createView];

    }

    return self;

}

- (void)createView{

    self.newsWebView = [[WKWebView alloc] init];

    self.newsWebView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, 0);

    self.newsWebView.navigationDelegate = self;

    self.newsWebView.scrollView.scrollEnabled = NO;

    [self.newsWebView sizeToFit];

    [self.contentView addSubview:self.newsWebView];

    //

    self.line = [[UIView alloc] init];

    [self.contentView addSubview:self.line];

    self.line.backgroundColor = [UIColor lightGrayColor];

}

- (void)refreshWebView:(NSString *)url indexPath:(NSInteger)index{

    self.indexPath = index;

    //// headerString 的添加是解决wkwebview 加载HTML是字体太小的问题

    NSString *headerString = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>";

    [self.newsWebView loadHTMLString:[headerString stringByAppendingString:url] baseURL:nil];

}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation*)navigation{


}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation*)navigation{

    

    [webView evaluateJavaScript:@"document.body.scrollHeight"completionHandler:^(id _Nullable result,NSError * _Nullable error){

        CGFloat height = [result floatValue];

        self.newsWebView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, height);

        [self.delegate webViewDidFinishLoad:height cellIndex:self.indexPath];

        self.line.frame = CGRectMake(0, height-0.5, self.contentView.frame.size.width, 0.5);

    }];

}







猜你喜欢

转载自blog.csdn.net/flg1554112450/article/details/80512010