iOS使用NSMutableAttributedString改变字符串中部分文字的字体颜色或大小

// 创建一个文本标签
UILabel *yyLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 300, 500)];
yyLabel.numberOfLines = 0;
// 创建NSMutableAttributedString做富文本操作 -- 设置字符串
NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:@"好好学习天天向上好好学习天天向上天天向上"];
// 改变字体大小
[attributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:NSMakeRange(3, 5)];
// 改变字体颜色
[attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor magentaColor] range:NSMakeRange(3, 5)];
// 将改变后的字符串添加到 label 上
yyLabel.attributedText = attributedStr;
[self.view addSubview:yyLabel];

相关属性:
设置字体: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

你可能感兴趣的:(OC,富文本,UI控件)