<原>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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM