<原>DTCoreText学习(一)-DTAttributedTextCell原理

其实DTCoreText自带的cell就很好用了,解析html并且显示html都很方便,只要设置DTAttributedTextCell的

- (void)setHTMLString:(NSString *)html方法即可,其原理如下面所示

 1 - (id)initWithReuseIdentifier:(NSString *)reuseIdentifier accessoryType:(UITableViewCellAccessoryType)accessoryType
 2 {
 3     self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
 4     if (self) 
 5     {
 6         // don't know size jetzt because there's no string in it
 7         _attributedTextContextView = [[DTAttributedTextContentView alloc] initWithFrame:CGRectZero];
 8         _attributedTextContextView.edgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
 9         [self.contentView addSubview:_attributedTextContextView];
10     }
11     return self;
12 }

这是DTAttributedTextCell中定义的初始化方法  在cell的contentView上覆盖了一层DTAttributedTextContentView 而我们的html正是通过它显示出来的,

 1 - (void)setHTMLString:(NSString *)html
 2 {
 3     // we don't preserve the html but compare it's hash
 4     NSUInteger newHash = [html hash];
 5     
 6     if (newHash == _htmlHash)
 7     {
 8         return;
 9     }
10     
11     _htmlHash = newHash;
12     
13     NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
14     NSAttributedString *string = [[NSAttributedString alloc] initWithHTML:data documentAttributes:NULL];
15     self.attributedString = string;
16 }
17 
18 - (void)setAttributedString:(NSAttributedString *)attributedString
19 {
20     if (_attributedString != attributedString)
21     {
22         _attributedString = attributedString;
23         
24         // passthrough
25         _attributedTextContextView.attributedString = _attributedString;
26     }
27 }

_attributedString的类型是NSAttributedString  我们把要显示的html传递给 setHTMLString:(NSString *)html   最后调用self.attributedString = string; 后进入setAttributedString:(NSAttributedString *)attributedString

最终设置  _attributedTextContextView.attributedString = _attributedString;达到显示的目的

DTAttributedTextCell常用的就这几个方法  一般了解这几个方法的使用  就能简单的实现利用 DTAttributedTextCell解析并显示html

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