TableViewCell嵌套webview

項目需求:UITableViewCell嵌套UIWebView,并且讓UIWebView根據內容自適應高度。

1 獲取UIWebView高度


- (void)webViewDidFinishLoad:(UIWebView *)webView

{

// 如果要獲取webView高度必須在網頁加載完成之后獲取

// 方法一

CGFloat height = [self.webView sizeThatFits:CGSizeZero].height;

// 方法二

CGFloat height = webView.scrollView.contentSize.height;

// 方法三 (不推薦使用,當webView.scalesPageToFit = YES計算的高度不準確)

CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];

}

2 UIWebView加載完成后cell高度的更新,使用通知來實現。

TableViewCell.m

- (void)webViewDidFinishLoad:(UIWebView *)webView

{

CGSize fittingSize = [self.webView sizeThatFits:CGSizeZero];

self.height = fittingSize.height;

self.webView.frame = CGRectMake(0, 0, fittingSize.width, fittingSize.height);

// 用通知發送加載完成后的高度

[[NSNotificationCenter defaultCenter] postNotificationName:@"WEBVIEW_HEIGHT" object:self userInfo:nil];

}

ViewController.m

- (void)viewDidLoad

{

[super viewDidLoad];

// 用于緩存cell高度

self.heightDic = [[NSMutableDictionary alloc] init];

// 注冊加載完成高度的通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti:) name:@"WEBVIEW_HEIGHT" object:nil];

}

- (void)noti:(NSNotification *)sender

{

TableViewCell *cell = [sender object];

if (![self.heightDic objectForKey:[NSString stringWithFormat:@"%ld",cell.tag]]||[[self.heightDic objectForKey:[NSString stringWithFormat:@"%ld",cell.tag]] floatValue] != cell.height)

{

[self.heightDic setObject:[NSNumber numberWithFloat:cell.height] forKey:[NSString stringWithFormat:@"%ld",cell.tag]];

[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:cell.tag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];

}

}

任何列表在同時加載很多條數據時都可能會出現類似問題,尤其是cell上面嵌套webview,可以采取一些方法避免:

(1)分頁加載(例如每頁20條)

(2)高度緩存,對于已經計算過高度的cell把計算過的高度存儲下次直接使用不進行二次高度計算

(3)定點更新,當高度計算完成(webview加載完成)后對指定cell刷新,而不是刷新全部cell

(4)占位處理,對于未加載完成的cell,用固定高度和內容進行占位,等webveiw加載完成后再顯示(這是可以非常有效的處理動態高度cell布局的閃屏問題)

參考鏈接:http://blog.zlcode.com/2016/04/28/ios-webview-cell/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容