美文网首页
iOS关于UILabel显示字体样式的一些技巧

iOS关于UILabel显示字体样式的一些技巧

作者: SacredBillows | 来源:发表于2016-04-14 10:50 被阅读1987次

好久没写过界面了,今天UI让改一个label。要求一个前面文字是一种颜色,后面文字是另外一种颜色和大小还需要倾斜。

突然发现到手边的东西给忘了,于是乎查阅了资料整理下来。以供大家参考和自己的回顾。

//利用NSMutableAtttibutedString 这个类给一个label上的文字设置两种颜色和两种大小

NSString *str1 = @"label上显示的字体";

NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc]initWithString:str1];

NSRange range1 = [str1 rangeOfString:@"上"];

NSRange range2 = [str1 rangeOfString:@"字"];

//设置"上"之前文字的颜色

[attributed addAttribute:NSForegroundColorAttributeName value:[UIColor cyanColor] range:NSMakeRange(0, range1.location)];

//设置"上"之前文字的大小

[attributed addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:NSMakeRange(0, range1.location)];

//设置"上"和"字"中间部分文字的颜色

[attributed addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(range1.location, range2.location - range1.location + 1)];

//设置"上"和"字"中间部分文字的样式和大小

//设置中文字体的倾斜角度

CGAffineTransform matrix =  CGAffineTransformMake(1, 0, tanf(8 * (CGFloat)M_PI / 180), 1, 0, 0);

UIFontDescriptor *desc = [ UIFontDescriptor  fontDescriptorWithName :[UIFont

systemFontOfSize :10 ]. fontName  matrix :matrix];

[attributed addAttribute:NSFontAttributeName value:  [UIFont fontWithDescriptor :desc  size :10] range:NSMakeRange(range1.location, range2.location - range1.location + 1)];

UILabel *titleLabel  = [[UILabel alloc]init];

//将设置好的字体样式复制给label。

titleLabel.attributedText = attributed;

titleLabel.adjustsFontSizeToFitWidth = YES;

titleLabel.numberOfLines = 2;

相关文章

网友评论

      本文标题:iOS关于UILabel显示字体样式的一些技巧

      本文链接:https://www.haomeiwen.com/subject/ndeglttx.html