日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

html 页面怎么加载富文本,UILabel加载html富文本

發布時間:2025/3/12 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 html 页面怎么加载富文本,UILabel加载html富文本 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文主要解決html標簽之外文本屬性設置

當APP里面有搜索的需求的時候,產品可能會要求關鍵字顯示特殊顏色或者字體。其中一種可能性是服務器返回的數據是帶有html標簽的字符串,那么該怎么解決?當標簽之外的其他字體也需要設置不同格式,又要怎么解決?

下面就來解決這個問題。

1.一個帶有html標簽的字符串

NSString * htmlString = @"紅色字體其他字體 紅色字體其他字體";

2.設置自己想要字體屬性

NSDictionary *dic = @{NSForegroundColorAttributeName: [UIColor grayColor],

NSBackgroundColorAttributeName: [UIColor clearColor],

NSFontAttributeName: [UIFont systemFontOfSize:15]};

3.顯示html格式的文本

NSMutableAttributedString * nameText = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes: nil error:nil];

第三步就是將html格式的文本轉化成字符串

4.解決除了html標簽之外的字體設置

void (^block)(NSDictionary*,NSRange,BOOL*) = ^(NSDictionary *attrs, NSRange range, BOOL *stop){

UIColor *color = attrs[NSForegroundColorAttributeName];

UIColor *colorRed = [UIColor redColor];

if (color && ![self isTheSameColor2:color anotherColor:colorRed]) {

[nameText addAttributes:dic range: range];

} else{

NSMutableDictionary *dicM = [attrs mutableCopy];

dicM[NSFontAttributeName ] = [UIFont systemFontOfSize:15];

[nameText addAttributes:dicM range: range];

}

};

[nameText enumerateAttributesInRange: NSMakeRange(0, nameText.length) options: NSAttributedStringEnumerationReverse usingBlock: block];

第四步就是解決其他文本屬性值的改變,這里只做了通過顏色來區別是html標簽文本還是其他文本,標簽里面是redColor,那么這里的判斷條件自然就是redColor,是通過isTheSameColor2: anotherColor:這個方法進行判斷

5.判斷方法的實現

- (BOOL) isTheSameColor2:(UIColor*)color1 anotherColor:(UIColor*)color2 {

if ([color1 red] == [color2 red] && [color1 green] == [color2 green] &&

[color1 blue] == [color2 blue] &&[color1 alpha] == [color2 alpha] ) {

return YES;

} else {

return NO;

}

}

6.寫一個UIColor的分類

#import "UIColor+RGB.h"

分類里面有四個屬性

@interface UIColor (RGB)

@property (nonatomic, readonly) CGFloat red;

@property (nonatomic, readonly) CGFloat green;

@property (nonatomic, readonly) CGFloat blue;

@property (nonatomic, readonly) CGFloat alpha;

@end

在 .m 文件中實現

- (CGFloat)red {

CGFloat r = 0, g, b, a;

[self getRed:&r green:&g blue:&b alpha:&a];

return r;

}

- (CGFloat)green {

CGFloat r, g = 0, b, a;

[self getRed:&r green:&g blue:&b alpha:&a];

return g;

}

- (CGFloat)blue {

CGFloat r, g, b = 0, a;

[self getRed:&r green:&g blue:&b alpha:&a];

return b;

}

- (CGFloat)alpha {

return CGColorGetAlpha(self.CGColor);

}

這個分類的作用在于比對顏色值,便于在第五步里面進行顏色的判斷

結果顯示

展示結果.png

但是如果只執行到第三步,那么紅色字體之外的顏色就是黑色

展示結果2.png

總結

以上是生活随笔為你收集整理的html 页面怎么加载富文本,UILabel加载html富文本的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。