有时候因为老板的要求或者UI的设计想法,我们会遇到需要把字体弄成各种各样的类型,这样就需要富文本文字来解决,所以在此把一些大神已经总结好的各种可能遇到的字体复制了一下,方便以后使用!!!
1、初始化
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
2、设置字体类型方法
//方法
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
//demo
[attrString addAttribute:NSFontAttributeName value:baseFont range:NSMakeRange(0, length)];
//name : 修改的富文本类型的名字,例如(NSFontAttributeName:字号、字体名;NSForegroundColorAttributeName:字体颜色)
3、各种字体举例
//系统默认字体类型
UIFont *baseFont = [UIFont systemFontOfSize:fontSize];
[attrString addAttribute:NSFontAttributeName value:baseFont range:NSMakeRange(0, length)];
//粗体
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
[attrString addAttribute:NSFontAttributeName value:boldFont range:[string rangeOfString:@"Text"]];
//设置倾斜,需要导入coreText
UIFont *italicFont = GetVariationOfFontWithTrait(baseFont,kCTFontTraitItalic);
[attrString addAttribute:NSFontAttributeName value:italicFont
range:[string rangeOfString:@"Label"]];
// 设置颜色
[attrString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:[string rangeOfString:@"ent"]];
//设置背景色
[attrString addAttribute:NSBackgroundColorAttributeName value:[UIColor blueColor] range:[string rangeOfString:@"ent"]];
//字体名称有以下:
[attrString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Verdana-BoldItalic" size:18] range:[string rangeOfString:@"Label"]];
//设置段落格式
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.lineSpacing = 10;//增加行高
style.headIndent = 10;//头部缩进,相当于左padding
style.tailIndent = -10;//相当于右padding
style.lineHeightMultiple = 1.5;//行间距是多少倍
style.alignment = NSTextAlignmentLeft;//对齐方式
style.firstLineHeadIndent = 20;//首行头缩进
style.paragraphSpacing = 10;//段落后面的间距
style.paragraphSpacingBefore = 20;//段落之前的间距
[attrString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, length)];
//字符间距 2pt
[attrString addAttribute:NSKernAttributeName value:@2 range:NSMakeRange(0, length)];
//设置文字描边颜色,需要和NSStrokeWidthAttributeName设置描边宽度,这样就能使文字空心
[attrString addAttribute:NSStrokeColorAttributeName value:[UIColor blueColor] range:[string rangeOfString:@"is"]];
//空心字,文字边框描述
[attrString addAttribute:NSStrokeWidthAttributeName value:@2 range:[string rangeOfString:@"is"]];
//下划线
[attrString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:[string rangeOfString:@"text"]];
//厚的下划线
[attrString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleThick) range:[string rangeOfString:@"label"]];
//删除线
[attrString addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:[string rangeOfString:@"things"]];
//删除线蓝色
[attrString addAttribute:NSStrikethroughColorAttributeName value:[UIColor blueColor] range:[string rangeOfString:@"things"]];