最近想实现一个功能,如图:
每月价格
最初实现的时候想到了用两个Label
,来实现,第一个显示¥4000
,设置一个字体,第二个显示/月
,设置另一个字体.这样就能实现这个效果了,但是最后想一想还是用富文本比较好,顺便可以学习一下.
今天我们先实现这个简单的效果.
先创建一个Label:
-(UILabel *)priceLabel{ if (_priceLabel == nil) { _priceLabel = [[UILabel alloc]init]; _priceLabel.font = kFONT(13); _priceLabel.textColor = kColorTheme; _priceLabel.textAlignment = NSTextAlignmentRight; } return _priceLabel; }
自己再创建一个私有方法,把字符串(比如:¥4000/月
)传进来,进行转换,返回富文本,赋值给所需要的Label.
-(NSMutableAttributedString *)getPriceAttribute:(NSString *)string{ NSMutableAttributedString *attribut = [[NSMutableAttributedString alloc]initWithString:string]; //目的是想改变 ‘/’前面的字体的属性,所以找到目标的range NSRange range = [string rangeOfString:@"/"]; NSRange pointRange = NSMakeRange(0, range.location); NSMutableDictionary *dic = [NSMutableDictionary dictionary]; dic[NSFontAttributeName] = [UIFont systemFontOfSize:18]; //赋值 [attribut addAttributes:dic range:pointRange]; return attribut; }
首先创建一个富文本NSMutableAttributedString
对象,把传进来的NSString
对象转化为NSMutableAttributedString
对象.
然后对NSMutableAttributedString
进行设置.NSRange range = [string rangeOfString:@"/"];
取到一个标志的位置:range
,然后对"/"前面的文字进行设置.
然后,返回富文本,再进行赋值.
_priceLabel.attributedText = [self getPriceAttribute:@"¥4000/月"];
上面只是一个简单应用,还有很多常用到的富文本.比如,文字和图片的混排,文字点击事件.等等.
NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:@"不要问我为什么编程,我喜欢手指在键盘上飞舞的感觉"]; [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5)]; [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 5)];
NSTextAttachment *attchImage = [[NSTextAttachment alloc] init];// 表情图片attchImage.image = [UIImage imageNamed:@"pic3"];// 设置图片大小attchImage.bounds = CGRectMake(0, -5, 20, 20);NSAttributedString *stringImage = [NSAttributedString attributedStringWithAttachment:attchImage]; [attriStr insertAttributedString:stringImage atIndex:2];
NSTextAttachment *attch = [[NSTextAttachment alloc] init];// 表情图片attch.image = [UIImage imageNamed:@"pic2"];// 设置图片大小attch.bounds = CGRectMake(0, -5, 20, 15);// 创建带有图片的富文本NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch]; [attriStr appendAttributedString:string];
[attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6, 4)]; [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(6, 4)];
NSDictionary * attriBute = @{NSForegroundColorAttributeName:[UIColor yellowColor],NSFontAttributeName:[UIFont systemFontOfSize:25]}; [attriStr addAttributes:attriBute range:NSMakeRange(10, 4)];
self.attrobiuteLabel.attributedText = attriStr;
效果图:
本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/ios-fuwenbenshiyong.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:3 月 19, 2019 at 04:40 下午