iOS中UILabel是我们很常用的一个控件,通过这个控件,我们可以展示诸如价格、电话、提示等内容。除了最基本的用法外,我们可以通过设置它的attributedText的各种属性来实现某一截内容加粗、变色或是被一条线贯穿的效果,就像商品原价那样。
首先在创建一个普通的UILabel控件,显示如图1:

这个就很普通的一个效果,更好的效果还得用attributedText实现。
label有一个attributedText属性,相信有人和我一样第一次看到attributed这个单词还是感到有些怕怕的,不过熟悉了就没啥了。
首先,创建NSMutableAttributedString对象,如图2:

往字典中加入AttributeName键值对便可实现相关富文本设置。图2中是对字符串range范围为(2,4)进行设置,即从3开始到6结束。
1,设置大字体,往字典加入NSFontAttributeName:[UIFont systemFontOfSize:50]键值对:

2,设置前景色为橙色,属性字典加入NSForegroundColorAttributeName:[UIColor orangeColor]:

3,设置文字描边,这里需要结合NSStrokeWidthAttributeName(设置描边宽度)一起实现,不然没有效果,属性字典加入NSStrokeColorAttributeName:[UIColor magentaColor]和NSStrokeWidthAttributeName:@3两个键值对:

NSStrokeWidthAttributeName设置后,可以看到前景色就没有了。NSStrokeWidthAttributeName所对应的value是一个 NSNumber 对象(小数)。该值改变描边宽度(相对于字体size 的百分比)。默认为 0,即不改变。正数只改变描边宽度。负数同时改变文字的描边和填充宽度。例如将NSStrokeWidthAttributeName的值改为-3后,效果如下:

4,设置倾斜字体,属性字典加入NSObliquenessAttributeName:@0.3键值对:

5,文字中间添加删除线,属性字典加入NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle)

这里横线的颜色是文本的前景色,即刚才的橙色,横线样式是一个枚举值,其他值效果可以自行试试。
6,文字添加阴影,这里需要提前创建阴影对象shadow,然后将此对象作为NSShadowAttributeName的值插入字典:

7,添加下划线,属性字典加入
NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)键值对:

8,设置段落样式,提前创建NSMutableParagraphStyle对象,作为NSParagraphStyleAttributeName的value插入字典:

因为这是设置段落样式的,这里只有一句话效果看不出来。
9,设置扁平化字体,属性字典插入NSExpansionAttributeName:@0.3键值对:

这里可以把0.3改为其他数字看看效果,比较夸张。
10,设置字间距,属性字典插入NSKernAttributeName:@5键值对:

NSKernAttributeName的值若为正值则间距加宽,负值间则距变窄。
还有其他的一些AttributeName,按住command点击上面任意一个AttributeName就可以进入相关的官方定义,可以看到还有很多属性,大家可以自行研究一下,如图14:

网友评论