记录label一些基本属性,包括常用的文字自适应高度,行间距等基本使用方法
self.label.textColor = [UIColor whiteColor];
self.label.text = @"whiteColor";self.label.preferredMaxLayoutWidth = self.view.frame.size.width;
// 点击按钮后设置highlighted和attributedText两个属性
- (IBAction)action:(UIButton *)sender {
self.label.highlighted = !self.label.highlighted;
/** 设置文本样式
NSFontAttributeName 字体默认是12号
NSParagraphStyleAttributeName 段落样式
NSForegroundColorAttributeName 指定字体颜色
NSBackgroundColorAttributeName 字体背景颜色
NSLigatureAttributeName 连体字符
NSKernAttributeName 字距的像素
NSStrikethroughStyleAttributeName指定字上加删除线
NSUnderlineStyleAttributeName 指定字加下划线
NSStrokeColorAttributeName 填充部分颜色
NSStrokeWidthAttributeName 填充宽度
NSShadowAttributeName 阴影
NSUnderlineColorAttributeName 下划线颜色
*/
NSMutableAttributedString *attributed = [[NSMutableAttributedStringalloc]initWithString:self.label.text];
// 设置第一个字符的颜色为黑色
[attributed addAttribute:NSForegroundColorAttributeNamevalue:[UIColorblackColor]range:NSMakeRange(0,1)];
self.label.attributedText = attributed;
}
/**
* 根据文字自动设置size
*/
- (CGSize)getCurrentTextSize {
CGSize size =CGSizeMake(MAXFLOAT,MAXFLOAT);
if (self.label.text.length > 0) {
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >=70000
size = [self.label.textboundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:self.label.font} context:nil].size;
#else
size = [self.text sizeWithFont:self.font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
#endif
}
return size;
}
/** 设置行间距 */
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 15;
NSDictionary*attrbut=@{NSFontAttributeName:self.font,NSParagraphStyleAttributeName:paragraphStyle};
NSMutableAttributedString*attributedText=[[NSMutableAttributedStringalloc]initWithString:self.text attributes:attrbut];
label.attributedText = attributedText;