您的位置:首页 > 其它

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

2012-09-02 14:18 281 查看
其实DTCoreText自带的cell就很好用了,解析html并且显示html都很方便,只要设置DTAttributedTextCell的

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

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


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

- (void)setHTMLString:(NSString *)html
{
// we don't preserve the html but compare it's hash
NSUInteger newHash = [html hash];

if (newHash == _htmlHash)
{
return;
}

_htmlHash = newHash;

NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *string = [[NSAttributedString alloc] initWithHTML:data documentAttributes:NULL];
self.attributedString = string;
}

- (void)setAttributedString:(NSAttributedString *)attributedString
{
if (_attributedString != attributedString)
{
_attributedString = attributedString;

// passthrough
_attributedTextContextView.attributedString = _attributedString;
}
}


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

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

DTAttributedTextCell常用的就这几个方法 一般了解这几个方法的使用 就能简单的实现利用 DTAttributedTextCell解析并显示html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: