专栏名称: Adrenine
iOS开发
目录
相关文章推荐
51好读  ›  专栏  ›  Adrenine

iOS笔记之UILabel(富文本)

Adrenine  · 掘金  ·  · 2017-12-13 08:46

正文

#1、常见的属性及说明

NSFontAttributeName  //字体
NSParagraphStyleAttributeName  //段落格式 
NSForegroundColorAttributeName  //字体颜色
NSBackgroundColorAttributeName  //背景颜色
NSStrikethroughStyleAttributeName  //删除线格式
NSUnderlineStyleAttributeName  //下划线格式
NSStrokeColorAttributeName  //删除线颜色
NSStrokeWidthAttributeName  //删除线宽度
NSShadowAttributeName  //阴影

#2、常见方法:

//为某一范围内文字设置多个属性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
//为某一范围内文字添加某个属性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
//为某一范围内文字添加多个属性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
//移除某范围内的某个属性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;

更多方法和属性说明详见 苹果官方说明文档

#3、使用示例:

NSString *str = @"犯我中华者,虽远必诛!";
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] 
      initWithString:str];
/*说明:NSAttributedString也能设置,与NSMutableAttributedString的关系类似于NSArray和NSMutableArray*/

(1)、添加字体和设置字体的范围

[attrStr addAttribute:NSFontAttributeName value:
  [UIFont systemFontOfSize:20.0f] range:NSMakeRange(0, 3)];  //字体大小为20.0f
[attrStr addAttribute:NSFontAttributeName value:
  [UIFont boldSystemFontOfSize:20.0f] range:NSMakeRange(0, 3)];  //字体大小为20.0f并且加粗

(2)、添加文字颜色

[attrStr addAttribute:NSForegroundColorAttributeName value:
  [UIColor redColor] range:NSMakeRange(0, 7)];

(3)、添加下划线

[attrStr addAttribute:NSUnderlineStyleAttributeName value:
  [NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, 7)];

(4)、设置段落样式

NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
//行间距
paragraph.lineSpacing = 10;
//段落间距
paragraph.paragraphSpacing = 20;
//对齐方式
paragraph.alignment = NSTextAlignmentLeft;
//指定段落开始的缩进像素
paragraph.firstLineHeadIndent = 30;
//调整全部文字的缩进像素paragraph.headIndent = 10;

(5)、添加段落设置

[attrStr addAttribute:NSParagraphStyleAttributeName value:paragraph 
  range:NSMakeRange(0, [str length])];

(6)、添加链接 label添加链接注意:label链接是可以显示出来,但是不能点击,而textView是可以点击的,因为里面有shouldInteractWithURL代理方法回调。







请到「今天看啥」查看全文