其實說是DTAttributedTextCell解析並顯示html 應該是cell上的DTAttributedTextContentView解析並顯示html
首先先說一下DTAttributedTextCell 解析顯示html的優點
a.能夠很好的實現cell的自適應高度,用webView也能實現自適應高度,但是邏輯復雜,效率不高,有加載延遲等等
b.能夠很好的進行內存管理,而webView顯示html的時候 內存很難管理,而且不會釋放內存
c.加載速度快,效率高
應用
1.首先將DTCoreText添加到自己的工程,具體方法參照DTCoreText目錄下的documentation文檔
2.向storyboard中拖入一個tableViewController 並將其class設為自己創建的子類,tableView 上面不需要cell 我門會在代碼里面創建cell
3.在XXXtableViewController.m中添加代碼:
1 #pragma mark UITableViewDataSource 2 3 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 4 return 1; 5 } 6 7 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 8 return 4; 9 } 10 11 - (void)configureCell:(DTAttributedTextCell *)cell forIndexPath:(NSIndexPath *)indexPath 12 { 13 14 15 NSString *html = @"hello boy"; 16 17 [cell setHTMLString:html]; 18 19 cell.attributedTextContextView.shouldDrawImages = YES; 20 } 21 22 - (DTAttributedTextCell *)tableView:(UITableView *)tableView preparedCellForIndexPath:(NSIndexPath *)indexPath 23 { 24 static NSString *cellIdentifier = @"cellIdentifier"; 25 26 if (!cellCache) 27 { 28 cellCache = [[NSCache alloc] init]; 29 } 30 31 // workaround for iOS 5 bug 32 NSString *key = [NSString stringWithFormat:@"%d-%d", indexPath.section, indexPath.row]; 33 34 DTAttributedTextCell *cell = [cellCache objectForKey:key]; 35 36 if (!cell) 37 { 38 // reuse does not work for variable height 39 //cell = (DTAttributedTextCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 40 41 if (!cell) 42 { 43 //用代碼創建cell 44 cell = [[DTAttributedTextCell alloc] initWithReuseIdentifier:cellIdentifier accessoryType:UITableViewCellAccessoryDisclosureIndicator]; 45 } 46 47 // cache it 48 [cellCache setObject:cell forKey:key]; 49 } 50 51 [self configureCell:cell forIndexPath:indexPath]; 52 53 return cell; 54 } 55 56 // disable this method to get static height = better performance 57 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 58 { 59 DTAttributedTextCell *cell = (DTAttributedTextCell *)[self tableView:tableView preparedCellForIndexPath:indexPath]; 60 61 return [cell requiredRowHeightInTableView:tableView]; 62 } 63 64 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 65 { 66 DTAttributedTextCell *cell = (DTAttributedTextCell *)[self tableView:tableView preparedCellForIndexPath:indexPath]; 67 68 return cell; 69 }
這樣便能將html 顯示到每個cell上 並且能自適應高度