属性字符串

来源:互联网 发布:python数组转字符串 编辑:程序博客网 时间:2024/06/01 13:37
iOS开发中,常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求。
 
     实例化方法:
使用字符串初始化
方法一:
- (id)initWithString:(NSString *)str;
例:
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"设置带属性的字符串"];
 
方法二:
- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;
: 
先创建一个字典,在字典中存放一些属性名和属性值:
NSDictionary *attributeDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [UIFont systemFontOfSize:15.0],NSFontAttributeName,
                                    [UIColor redColor],NSForegroundColorAttributeName,
                                   [NSNumber numberWithInter:NSUnderlineStyleSingle], NSUnderlineStyleAttributeName,nil];
 
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"设置带属性的字符串" attributes:attributeDict];
 
方法三:
-(id)initWithAttributedString:(NSAttributedString *)attester;
使用NSAttributedString初始化,跟NSMutableStringNSString类似
 
使用方法:
 
为某一范围内文字添加某个属性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
 
为某一范围内文字设置多个属性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
 
为某一范围内文字添加多个属性
  • (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
 
移除某范围内的某个属性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
  
     常见的属性及说明
 
字体 NSFontAttributeName 
 
段落格式: NSParagraphStyleAttributeName 
 
字体颜色 NSForegroundColorAttributeName 
  
背景颜色: NSBackgroundColorAttributeName
 
删除线格式: NSStrikethroughStyleAttributeName
 
下划线格式: NSUnderlineStyleAttributeName
      
删除线颜色: NSStrokeColorAttributeName 
 
删除线宽度: NSStrokeWidthAttributeName
 
阴影: NSShadowAttributeName
 
使用实例
   UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 30)];
   testLabel.backgroundColor = [UIColor lightGrayColor];
   testLabel.textAlignment = NSTextAlignmentCenter;
   NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"设置带属性的字符串"];
   [AttributedStr addAttribute:NSFontAttributeName
                         value:[UIFont systemFontOfSize:16.0]
                         range:NSMakeRange(2, 2)];
   [AttributedStr addAttribute:NSForegroundColorAttributeName
                         value:[UIColor redColor]
                         range:NSMakeRange(2, 2)];
   testLabel.attributedText = AttributedStr;
   [self.view addSubview:testLabel];属性字符串
0 0