UILabel* noteLabel = [[UILabel alloc] init];
noteLabel.frame = CGRectMake(0, 100, 200, 100);
noteLabel.textColor = [UIColor blackColor];
NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:@”1111:2222”];
NSRange redRange = NSMakeRange(0, [[noteStr string] rangeOfString:@”:”].location);
[noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];
[noteLabel setAttributedText:noteStr] ;
[noteLabel sizeToFit];
[self.view addSubview:noteLabel];
补充 NSMutableParagraphStyle *paragraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease];
[paragraphStyle setLineSpacing:LINESPACE];//调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [contentStr length])];
换行需要设置numberOfLines = 0
使用方法:
为某一范围内文字设置多个属性
- (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
阴影