11.同一个Label中显示不同字体(NSAttributedString)

来源:互联网 发布:hbuilder 编辑器无php 编辑:程序博客网 时间:2024/05/21 09:32

在开发中经常碰到一句话, 显示的字体大小或者颜色不同的情况,如下图情况。 当然可以用多个 UILabel 去显示, 但是性能和繁杂程度的角度来说 , 在同一个 Label 中使用NSMutableAttributedString 类会更加方便。而且还有很多更多的功能,如添加下划线,双下划线等等, 接下来,我们一起来看看。
这里写图片描述

首先, 你要准备几种字体,你可以参考 9. iOS 开发中添加自定义汉语字体 文章中如何获取所有的字体类型的方法, 也可以参考 8.iOS 字体类型列表 文章中的字体类型。

UILabel 有个属性attributedText, 该属性默认为 nil, 当设置了该属性后,其他关于 label.text 的属性就会失效。

// the underlying attributed string drawn by the label, if set, the label ignores the properties above.
@property(nullable, nonatomic,copy) NSAttributedString *attributedText NS_AVAILABLE_IOS(6_0); // default is nil

NSMutableAttributedString类中常用的三个方法:

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;- (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range;- (void)removeAttribute:(NSString *)name range:(NSRange)range;//

1.addAttribute: value: range: 方法使用, 可以对某个给定的 range 进行字体颜色或者大小或者风格的特质属性添加。

NSMutableAttributedString *newAttrStr = [[NSMutableAttributedString alloc] initWithString:@"1071.22元"];[newAttrStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:40] range:NSMakeRange(0,length)];[newAttrStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:18] range:NSMakeRange(length,1)];accountMoneyLabel.attributedText = newAttrStr;//

以上代码的结果是上图展示的内容。

2.addAttributes: range: 方法使用, 只可以对某个给定的 range 进行字体颜色和大小和风格的特质属性添加。注意此处用词为”和”不是”或”,第一种方法在一行代码下只可以做出某一种改变, 本方法可以做出多种改变。(第一种方法多次添加几种改变,效果可达到一致)

NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString: @"最低¥8.88元"];[currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:13],NSForegroundColorAttributeName:[UIColor brownColor],NSUnderlineStyleAttributeName:[NSNumber numberWithInt:NSUnderlineStyleDouble]} range:NSMakeRange(0, 2)];[currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Verdana-Italic" size:22],NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(2, 5)];Label.attributedText = currentPriceStr;//

结果展示
这里写图片描述

3.removeAttribute: range: 方法, 移除某个给定范围的特质属性。

Attributes

在NSAttributedString.h文件中, 有各种可添加的Attributes和Attribute values, 常用的有字体名称/前景色/背景色/下划线风格等等, 具体的可以慢慢探究。
这里写图片描述

延伸资料:iOS NSAttributedString所有文本属性详解(多图)

0 0