MDHTMLLabel —— 轻量级 HTML 文本的解决方案

jopen 8年前

对于复杂的文本格式,后端同学给你的往往会是 HTML,而 iOS 除了 WebView 和一个巨卡无比的 TextView 渲染方案,并没有别的选择。

上一期 使用 TextKit 定制全功能的 TextView ,我们使用了 TextKit 以及正则匹配的方法实现了对特定格式的文本解析。

MDHTMLLabel 则是基于 CoreText 用正则对 HTML 进行了解析,实现了一个轻量级的方案,项目代码使用 Objective-C 编写,支持 Swift 项目调用。

MDHTMLLabel *htmlLabel = [[MDHTMLLabel alloc] initWithFrame:frame];    htmlLabel.delegate = self;    htmlLabel.htmlText = htmlText;  

对于文本的样式也是非常容易定制,利用 AttributedText 即可实现

htmlLabel.linkAttributes = @{    NSForegroundColorAttributeName: [UIColor blueColor],    NSFontAttributeName: [UIFont boldSystemFontOfSize:htmlLabel.font.pointSize],    NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle) };    htmlLabel.activeLinkAttributes = @{    NSForegroundColorAttributeName: [UIColor redColor],    NSFontAttributeName: [UIFont boldSystemFontOfSize:htmlLabel.font.pointSize],    NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle) };  

另外一个很重要的就是高度计算问题,利用其提供的一个类方法也是可以轻松实现。

+ (CGFloat)sizeThatFitsHTMLString:(NSString *)htmlString                           withFont:(UIFont *)font                        constraints:(CGSize)size             limitedToNumberOfLines:(NSUInteger)numberOfLines                     autoDetectUrls:(BOOL)autoDetectUrls;

来自: http://tips.producter.io/mdhtmllabel-ge-chu-li-html-wen-ben-de-jue-jia-xuan-ze-2/