label.adjustsFontSizeToFitWidth = YES; 让字体自适应label
label.numberOfLines = [label.text length]; 竖向显示文本
UILabel 高度根据内容多少来改变
#import
@interface UILabel (BoundingRect)
//初始化的size,size中高度或者宽度为0
-(CGRect)boundingRectWithInitSize:(CGSize)size;
@end
UILabel+BoundingRect.m
#import "UILabel+BoundingRect.h"
@implementation UILabel (BoundingRect)
-(CGRect)boundingRectWithInitSize:(CGSize)size
{
self.lineBreakMode=NSLineBreakByWordWrapping;
CGRect rect=[self.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:self.font,NSFontAttributeName, nil] context:nil];
return rect;
}
@end
//给定宽度,要知道label的高度
self.label=[[UILabel alloc]initWithFrame:CGRectMake(100, 100, 200, 0)];
self.label.font=[UIFont fontWithName:@"HelveticaNeue" size:18.0f];
self.label.text=@"潇洒哥:最近怎样?在那里呆的还习惯吗?哪天聚一聚,一起吃顿饭";
self.label.textColor=[UIColor darkGrayColor];
[self.view addSubview:self.label];
self.label.numberOfLines=0; //PS:这句很主要,否则默认行数为1,只显示一行文字后面截断了就没有了
CGRect myRect=[self.label boundingRectWithInitSize:self.label.frame.size];
self.label.frame=CGRectMake(100, 100, 200, myRect.size.height+100);
反之,也可以固定高度,来确定label的宽度。
在UILabel显示不同的字体和颜色
UILabel *matchScoreLabel = [[UILabel alloc] initWithFrame:...];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@
"Using NSAttributed String"
];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,4)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(0, 5)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0] range:NSMakeRange(6, 12)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(19, 6)];
matchScoreLabel.attributedText = str;