今天使用Label的时候,需要计算UILabel的高度,发现在4,4s上显示正常,在iPhone5s、iphone6上显示出错
使用的方法为:
NSString *teacherComment = @"评语是写给学生看的,所以一方面评语要使用学生能看得懂的英语来写,所使用的词汇和语法不能过高或过低于学生的现有水平,要切合学生的实际水平,符合学生的个性心理...";
float commentHeight = 0.0;
if ([teacherComment isEqual:@""]||teacherComment==nil||[[NSNull null] isEqual:teacherComment]) {
commentHeight = BASIC_LABEL_HEIGHT;
}else{
CGSize commentRect = [teacherComment sizeWithFont:[UIFont fontWithName:TITLE_FONT size:FONT_SIZE_FOURTEEN] constrainedToSize:CGSizeMake(180, CGFLOAT_MAX) lineBreakMode:NSLineBreakByCharWrapping];
if (commentRect.height > BASIC_LABEL_HEIGHT) {
commentHeight = commentRect.height;
}
else
{
commentHeight = BASIC_LABEL_HEIGHT;
}
}
这段代码在iPhone4或iPhone4s上显示正常,系统分别是ios7,ios8的系统。但是在iphone5s与iphone6的真机上运行后发现少了显示不正常,有些误差。
这个问题很奇怪了,在此记录,上网搜索一下,使用一下方法即可:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = @{NSFontAttributeName:[UIFont fontWithName:TITLE_FONT size:FONT_SIZE_FOURTEEN], NSParagraphStyleAttributeName:paragraphStyle.copy};
CGSize labelSize = [teacherCommentLabel.text boundingRectWithSize:CGSizeMake(180.0f, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
labelSize.height = ceil(labelSize.height);
labelSize.width = ceil(labelSize.width);
if (labelSize.height > BASIC_LABEL_HEIGHT) {
commentHeight = labelSize.height;
}
else
{
commentHeight = BASIC_LABEL_HEIGHT;
}
使用的时候还需要判断系统版本,所以需要注意一下,如果是ios7则使用该方法,ios6则使用上面的一个方法。
误差如图所示:
如果您有什么好的方法,请留言告知,谢谢。。。
延伸阅读:www.wahenzan.com