UILabel的text设置不同颜色、字体

来源:互联网 发布:网络本科学历可以考研 编辑:程序博客网 时间:2024/06/03 21:21

下载地址 GitHub源码 或 Demo下载

在项目开发中,经常会遇到同一行文本显示的字体颜色和大小不一样,看着可以使用两个label来进行布局,实则显得麻烦,因为设置固定字体大小,那么在不同屏幕大小的手机有可能文本之间显示有间隙,也有可能出现......,这样还是在同一个label中显示比较好。如下:

- (void)viewDidLoad {    [super viewDidLoad];        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(80, 100, 200, 300)];    label.textColor = [UIColor blackColor];    label.numberOfLines = 0;    label.font = [UIFont systemFontOfSize:12];    [self.view addSubview:label];        //不同字体颜色    float unit = 2.123;    NSString *strNumber = [NSString stringWithFormat:@"单价价值:1人次/¥%@",[NSString stringWithFormat:@"%.2f",unit]];    NSMutableAttributedString *str_number = [[NSMutableAttributedString alloc] initWithString:strNumber];    NSString *strLength = [NSString stringWithFormat:@"¥%.2f",unit];    [self setDiffString:str_number withString:@"单价" loaction:0 textColor:[UIColor redColor] textSize:@"Arial-BoldItalicMT" size:30.0];    [self setDiffString:str_number withString:strLength loaction:9 textColor:[UIColor greenColor] textSize:@"HelveticaNeue-Bold" size:10.0];    label.attributedText = str_number;}#pragma mark - 同一label设置不同颜色、字体- (void)setDiffString:(NSMutableAttributedString *)str_number withString:(NSString *)str_jq loaction:(NSInteger)loca textColor:(UIColor *)color textSize:(NSString *)fontName size:(CGFloat)size{    [str_number addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(loca,[str_jq length])];    [str_number addAttribute:NSFontAttributeName value:[UIFont fontWithName:fontName size:size] range:NSMakeRange(loca,[str_jq length])];}

效果如下:


4 0
原创粉丝点击