1、NSAttributeString简介学习
NSAttributedString叫作富文本,是一种带有属性的字符串,经过它能够轻松的在一个字符串中表现出多种字体、字号、字体大小等各不相同的风格,还能够对段落进行格式化。字体
2、字符属性spa
1.NSString *const NSFontAttributeName(字体):code
该属性所对应的值是一个 UIFont 对象。该属性用于改变一段文本的字体。若是不指定该属性,则默认为12-point Helvetica(Neue)。orm
2.NSString *const NSParagraphStyleAttributeName(段落):对象
该属性所对应的值是一个 NSParagraphStyle 对象。该属性在一段文本上应用多个属性。若是不指定该属性,则默认为 NSParagraphStyle 的 defaultParagraphStyle 方法返回的默认段落属性。想要了解NSParagraphStyle能够自行百度学习,在这里不详细描述。注意:lable的numberOfLines属性必须设置为0,段落样式才能生效。blog
3.NSString *const NSForegroundColorAttributeName(字体颜色):字符串
该属性所对应的值是一个 UIColor 对象。该属性用于指定一段文本的字体颜色。若是不指定该属性,则默认为黑色。string
4.NSString *const NSBackgroundColorAttributeName(字体背景色):it
该属性所对应的值是一个 UIColor 对象。该属性用于指定一段文本的背景颜色。若是不指定该属性,则默认无背景色。
5.NSString *const NSLigatureAttributeName(连字符):
该属性所对应的值是一个 NSNumber 对象(整数)。连体字符是指某些连在一块儿的字符,它们采用单个的图元符号。0 表示没有连体字符。1 表示使用默认的连体字符。2表示使用全部连体符号。默认值为 1(注意,iOS 不支持值为 2)。
6.NSString *const NSKernAttributeName(字间距):
该属性所对应的值是一个 NSNumber 对象(整数)。连体字符是指某些连在一块儿的字符,它们采用单个的图元符号。0 表示没有连体字符。1 表示使用默认的连体字符。2表示使用全部连体符号。默认值为 1(注意,iOS 不支持值为 2)。
7.NSString *const NSStrikethroughStyleAttributeName(删除线):
该属性所对应的值是一个 NSNumber 对象(整数)。该值指定是否在文字上加上删除线,该值参考“Underline Style Attributes”。默认值是NSUnderlineStyleNone。
8.NSString *const NSUnderlineStyleAttributeName(下划线):
该属性所对应的值是一个 NSNumber 对象(整数)。该值指定是否在文字上加上下划线,该值参考“Underline Style Attributes”。默认值是NSUnderlineStyleNone。
9.NSString *const NSStrokeColorAttributeName(边线颜色):
该属性所对应的值是一个 UIColor 对象。若是该属性不指定(默认),则等同于 NSForegroundColorAttributeName。不然,指定为删除线或下划线颜色。更多细节见“Drawing attributedstrings that are both filled and stroked”。
10.NSString *const NSStrokeWidthAttributeName(边线宽度):
该属性所对应的值是一个 NSNumber 对象(小数)。该值改变描边宽度(相对于字体size 的百分比)。默认为 0,即不改变。正数只改变描边宽度。负数同时改变文字的描边和填充宽度。例如,对于常见的空心字,这个值一般为3.0。
11.NSString *const NSShadowAttributeName(阴影):
该属性所对应的值是一个 NSShadow 对象。默认为 nil。
12.NSString *const NSVerticalGlyphFormAttributeName(横竖排版):
该属性所对应的值是一个 NSNumber 对象(整数)。0 表示横排文本。1 表示竖排文本。在 iOS 中,老是使用横排文本,0 之外的值都未定义。
3、代码示例
在这里给你们举了几个简单的例子,有兴趣的能够尝试其他属性的效果。
// 示例Lable UILabel *exLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 40)]; exLabel.textAlignment = NSTextAlignmentCenter; [self.view addSubview:exLabel]; NSString *exString = @"查看人数:150人"; // 富文本对象 NSMutableAttributedString *exAttributedString = [[NSMutableAttributedString alloc] initWithString:exString]; // 富文本样式 // 经过addAttribute方法设置样式 // 参数分别是字符属性,值,改变范围 // 字体颜色 [exAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5, 4)]; // 字体大小 [exAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:NSMakeRange(5, 4)]; // 背景颜色 [exAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(5, 4)]; // 字间距 [exAttributedString addAttribute:NSKernAttributeName value:[NSNumber numberWithInt:5] range:NSMakeRange(5, 4)]; exLabel.attributedText = exAttributedString;
效果图: