<原>DTCoreText学习(二)-DTAttributedTextCell应用

其实说是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上  并且能自适应高度

posted @ 2012-09-02 14:46  不曾拥有  阅读(4991)  评论(0编辑  收藏  举报