废话不多说,直接上代码
第一段代码主要是创建富文本,并给文字赋值给label,调整文字的颜色字体行间距等
- (void)createLabel
{
UILabel * textLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 250, 200, 20)];
textLabel.backgroundColor = [UIColor yellowColor];
//调整行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 10;// 字体的行间距
//设置字体大小
textLabel.font = [UIFont systemFontOfSize:15.0];
textLabel.numberOfLines = 0;
NSDictionary * attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:15.0],NSParagraphStyleAttributeName:paragraphStyle};
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"如果一个属性总是使用同一个初始值,可以为其设置一个默认值。无论定义默认值还是在构造器中赋值,最终它们实现的效果是一样的,只不过默认值将属性的初始化和属性的声明结合的更紧密。使用默认值能让你的构造器更简洁、更清晰,且能通过默认值自动推导出属性的类型;同时,它也能让你充分利用默认构造器、构造器继承(后续章节将讲到)等特性。" attributes:attribute];
//设置字体不同的颜色
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 50)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(50, str.length - 50)];
[textLabel setAttributedText:str];
[self addSubview:textLabel];
//计算文字高度并调整lable高度
CGFloat height = [self setNameLabelWithText:str attribute:attribute];
textLabel.frame = CGRectMake(10, 250, 200, height);
}
第二段通过文字属性计算label的高度,这个方法在开发过程中会经常用到。
- (CGFloat)setNameLabelWithText:(NSMutableAttributedString *)text attribute:(NSDictionary *)attribute
{
NSString * str = [text string];
CGRect textRext = [str boundingRectWithSize:CGSizeMake(200, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil];
CGFloat height = textRext.size.height;
return height;
}
运行结果是酱紫的