+ (NSMutableAttributedString *)formatText:(NSString *)text {
NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
NSError *error = nil;
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:&error];
if (error) {
NSLog(@"HTML 解析錯誤: %@", error);
return [[NSMutableAttributedString alloc] init];
}
// 創(chuàng)建可變富文本
NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
// 遍歷整個富文本的范圍,移除背景色屬性
[mutableAttributedString enumerateAttribute:NSBackgroundColorAttributeName
inRange:NSMakeRange(0, mutableAttributedString.length)
options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (value) {
[mutableAttributedString removeAttribute:NSBackgroundColorAttributeName range:range];
}
}];
// 設置字體
[mutableAttributedString beginEditing];
[mutableAttributedString enumerateAttribute:NSFontAttributeName
inRange:NSMakeRange(0, mutableAttributedString.length)
options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (value) {
UIFont *newFont = [UIFont systemFontOfSize:14];
[mutableAttributedString addAttribute:NSFontAttributeName value:newFont range:range];
}
}];
[mutableAttributedString endEditing];
// 設置字體行間距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 1.5;
[mutableAttributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, attributedString.length)];
// 設置文本顏色
[mutableAttributedString enumerateAttribute:NSBackgroundColorAttributeName
inRange:NSMakeRange(0, mutableAttributedString.length)
options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (value) {
[mutableAttributedString removeAttribute:NSBackgroundColorAttributeName range:range];
}
}];
[mutableAttributedString addAttribute:NSForegroundColorAttributeName
value:hexColor(333333)
range:NSMakeRange(0, attributedString.length)];
return mutableAttributedString;
}
使用富文本解析html
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內容
- 參考:android 開發(fā)--抓取網(wǎng)頁解析網(wǎng)頁內容的若干方法(網(wǎng)絡爬蟲)(正則表達式) 網(wǎng)頁有兩種格式,一種是xm...
- 【知識點】 一. 數(shù)據(jù)的網(wǎng)絡請求 【注】大多數(shù)APP都是依托于服務器的,由服務器負責數(shù)據(jù)的管理交互,分發(fā),篩選等等...
- TFHpple是一個XML/HTML解析框架,我們可以用來解析從后臺發(fā)送過來的HTML數(shù)據(jù)。如果要在項目中使用這個...
- 本項目由微信小程序開發(fā)論壇-WeAppDev http://weappdev.com/ 會員開發(fā) 原文地址: ht...