self.label.text = @"....";
计算 frame 的最新方法
//1.设置lable最大显示行数
self.label.numberOfLines = 0;
//2.写出字体的字号
NSDictionary *attrs = @{NSFontAttributeName : [UIFont systemFontOfSize:15]};
//3.根据显示区域的限制 (如CGSizeMake(375.0, 40.0)) 求出一个框架的size
CGRect rect = [self.label.text boundingRectWithSize:CGSizeMake(375.0, 40.0) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil];
例如
NSDictionary *attrs = @{NSFontAttributeName :[UIFont systemFontOfSize:15]};
CGRect rect = [@"..." boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil];
附上函数抽取
-(void)calculateFrameOfLabel:(UILabel *)lab andAddValue:(CGFloat)value{
lab.numberOfLines = 0;
lab.font = kFontSize_24;
NSDictionary * attributes = [NSDictionary dictionaryWithObject:lab.font forKey:NSFontAttributeName];
CGRect rect = [lab.text boundingRectWithSize:CGSizeMake(kScreenWidth - 12-12, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
lab.frame = CGRectMake(12, value, kScreenWidth - 24, rect.size.height);
}
有人说这么写
+ (CGSize )viewHeight:(CGSize )withd :(float)thfont :(NSString*)text
{
CGSize size;
if(IOS_7>=7.0)
{
NSDictionary * attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:thfont]forKey:NSFontAttributeName];
NSAttributedString *attributedText =[[NSAttributedString alloc]initWithString:text attributes:attributes];
CGRect rect = [attributedText boundingRectWithSize:withd
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
size = rect.size;
}
else
{
//设置label的最大行数
size = [text sizeWithFont:[UIFont systemFontOfSize:thfont]constrainedToSize:withd lineBreakMode:NSLineBreakByClipping];
}
return size;
}