需求:每个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