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富文本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: zookeeper一键启动关闭JAVA_
- 下一篇: 启动马达接线实物图_电工外出接单从事配电