uilabel 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);

}

这个分类的作用在于比对颜色值,便于在第五步里面进行颜色的判断

结果显示

931b9200b101?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

展示结果.png

但是如果只执行到第三步,那么红色字体之外的颜色就是黑色

931b9200b101?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

展示结果2.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值