常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求。
使用富文本NSMuttableAttstring(带属性的字符串),上面的一些需求都可以很简便的实现。
每月价格
最初实现的时候想到了用两个标签,来实现,第一个显示円4000年,设置一个字体,第二个显示/月,设置另一个字体。这样就能实现这个效果了,但是最后想一想还是用富文本比较好,顺便可以学习一下。
先创建一个标签:
——(UILabel *) priceLabel { 如果(_priceLabel==nil) { _priceLabel=[[UILabel alloc] init); _priceLabel。字体=kFONT (13); _priceLabel。输入textColor=kColorTheme; _priceLabel。textAlignment=NSTextAlignmentRight; } 返回_priceLabel; }
自己再创建一个私有方法,把字符串(比如:円4000/月)传进来,进行转换,返回富文本,赋值给所需要的标签。
——(NSMutableAttributedString *) getPriceAttribute:字符串(NSString *) { NSMutableAttributedString * attribut=[] [NSMutableAttributedString alloc] initWithString:字符串;//目的是想改变“/鼻懊娴淖痔宓氖粜?所以找到目标的范围 NSRange范围=(字符串rangeOfString: @“/?; NSRange pointRange=NSMakeRange (0, range.location); 称为unaryoperations * dic=(称为unaryoperations字典); dic [NSFontAttributeName]=[UIFont systemFontOfSize: 18);//赋值 [attribut addattribute: dic范围:pointRange]; 返回attribut; }
首先创建一个富文本NSMutableAttributedString对象,把传进来的NSString对象转化为NSMutableAttributedString对象。
然后对NSMutableAttributedString进行设置。
<代码> NSRange范围=(字符串rangeOfString: @“/?; 代码>取到一个标志的位置:范围,然后对“/鼻懊娴奈淖纸猩柚谩?/p>
然后,返回富文本,再进行赋值。
_priceLabel。attributedText=[自我getPriceAttribute: @ 4000/月円”);>之前上面只是一个简单应用,还有很多常用到的富文本。比如,文字和图片的混排,文字点击事件。等等。
我们依次实现一些功能
在指定位置添加图片
NSMutableAttributedString * attriStr=[[NSMutableAttributedString alloc] initWithString: @”不要问我为什么编程,我喜欢手指在键盘上飞舞的感觉”); [attriStr addAttribute: NSForegroundColorAttributeName价值:(用户界面颜色blueColor)范围:NSMakeRange (0 5)]; [attriStr addAttribute: NSFontAttributeName价值:[UIFont systemFontOfSize: 20)范围:NSMakeRange (0 5)];添加图片到指定的位置
NSTextAttachment * attchImage=[[NSTextAttachment alloc] init);//表情图片 attchImage。形象=[界面图像imageNamed: @“pic3”);//设置图片大小 attchImage。边界=CGRectMake (0、5、20、20); NSAttributedString * stringImage=[NSAttributedString attributedStringWithAttachment attchImage):; [attriStr insertAttributedString: stringImage atIndex: 2];追加图片到最后一位
NSTextAttachment *填写=[[NSTextAttachment alloc] init);//表情图片 填写。形象=[界面图像imageNamed: @“pic2”);//设置图片大小 填写。边界=CGRectMake (0、5、20、15);//创建带有图片的富文本 NSAttributedString *字符串=[NSAttributedString attributedStringWithAttachment:填写); [attriStr appendAttributedString: string];设置中间位置文字为红色
[attriStr addAttribute: NSForegroundColorAttributeName价值:(用户界面颜色redColor)范围:NSMakeRange (6,4)]; [attriStr addAttribute: NSFontAttributeName价值:[UIFont systemFontOfSize: 30)范围:NSMakeRange (6,4)];综合写法
NSDictionary *属性=@ {NSForegroundColorAttributeName:(用户界面颜色yellowColor], NSFontAttributeName: [UIFont systemFontOfSize: 25)}; [attriStr addattribute:属性范围:NSMakeRange (10, 4)]; self.attrobiuteLabel。attributedText=attriStr;效果图: