在项目开发中,我们经常会遇到在这样情形:
1、在一个UILabel 使用不同的颜色或不同的字体来体现字符串
在iOS 6 以后我们可以很轻松的实现这一点,官方的API 为我们提供了UILabel类的attributedText, 使用不同颜色和不同字体的字符串,我们可以使用NSAttributedText 和 NSMutableAttributedText 类来实现。
UILabel *labelStr = [[UILabel alloc]initWithFrame:(CGRectMake(30, 130, 300, 30))];
labelStr.text = @"iOS 在UILabel显示不同的字体和颜色";
labelStr.textColor = [UIColor lightGrayColor];
labelStr.font = [UIFont systemFontOfSize:15];
[self.view addSubview:labelStr];
NSMutableAttributedString *newStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"AAA:%@", labelStr.text]];
// 设置指定区域字体颜色
[newStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 4)];
// 设置指定区域字体样式和大小
[newStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:12] range:NSMakeRange(0, 4)];
labelStr.attributedText = newStr;
2、在开发商城APP时,我们会用到给文字加下划线,表示重视,给价格加中划线表示打折了
// label添加下划线
UILabel *label = [[UILabel alloc]initWithFrame:(CGRectMake(20, 20, 300, 30))];
label.text = @"给Label添加下划线,表示为可点属性";
label.textColor = [UIColor blueColor];
NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]};
NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:label.text attributes:attribtDic];
//赋值
label.attributedText = attribtStr;
[self.view addSubview:label];
// label加中划线
UILabel *label2 = [[UILabel alloc]initWithFrame:(CGRectMake(20, 60, 300, 30))];
label2.text = @"给Label添加中划线,表示为打折出售";
//中划线
NSDictionary *attribtDic2 = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
NSMutableAttributedString *attribtStr2 = [[NSMutableAttributedString alloc]initWithString:label2.text attributes:attribtDic2];
// 赋值
label2.attributedText = attribtStr2;
[self.view addSubview:label2];
3、在文字后面直接显示图片,让图片始终能恰好的在文字后面。
有时文字的多少是不确定的,这时就需要我们判断这些文字的宽和高,以便于正确定义label的位置大小
NSString *layoutStr = @"iOS UILabel自适应宽度";
UILabel *label3 = [[UILabel alloc]initWithFrame:(CGRectMake(30, 180, 0, 0))];
label3.textColor = [UIColor lightGrayColor];
label3.backgroundColor = [UIColor yellowColor];
label3.font = [UIFont systemFontOfSize:15];
[self.view addSubview:label3];
label3.text = layoutStr;
// 获取这段文字的宽和高
CGSize size = [self SizeOfText:layoutStr withFont:[UIFont systemFontOfSize:15]];
CGRect frame = label3.frame;
frame.size.width= size.width;
frame.size.height= size.height;
label3.frame = frame;
UIImageView *imageView = [[UIImageView alloc]initWithFrame:(CGRectMake(label3.right + 5, label3.top, 20, 20))];
imageView.image = [UIImage imageNamed:@"Home"];
[self.view addSubview:imageView]; }
// 获取这段文字的宽和高
-(CGSize)SizeOfText:(NSString *)text withFont:(UIFont *)font
{
CGSize size = [text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil]];
return size;
}