MDHTMLLabel —— 輕量級 HTML 文本的解決方案
對于復雜的文本格式,后端同學給你的往往會是 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/
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!