ios属性字符串

2020-01-08  本文已影响0人  小言_0480

-(NSMutableAttributedString *)attributedStringFromString:(NSString *)str{

    NSMutableAttributedString *aStr =[[NSMutableAttributedString alloc]initWithString:str];

    [aStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:(4*16+13)/256.0 green:(12*16+2)/256.0 blue:(15*16+3)/256.0 alpha:1.0]} range:NSMakeRange(5,str.length-5)];

   //[aStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:25*PO],NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(0,3)];

    return aStr;

}

给属性字符串加属性

http://blog.csdn.net/reylen/article/details/41208747

为某一范围内文字设置多个属性

-(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;

2.     常见的属性及说明

NSFontAttributeName 

字体

NSParagraphStyleAttributeName 

段落格式 

NSForegroundColorAttributeName 

字体颜色

NSBackgroundColorAttributeName  

背景颜色

NSStrikethroughStyleAttributeName

删除线格式

NSUnderlineStyleAttributeName     

下划线格式

NSStrokeColorAttributeName       

删除线颜色

NSStrokeWidthAttributeName

删除线宽度

NSShadowAttributeName 

阴影

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

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003689

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];

上一篇 下一篇

猜你喜欢

热点阅读