ios 计算文字占用高度
自动计算的方法:
- (CGFloat)contentCellHeightWithText:(NSString*)text { NSInteger ch; UIFont *font = [UIFont systemFontOfSize:17];//11 一定要跟label的显示字体大小一致 //设置字体 CGSize size = CGSizeMake(LCDW - 16, 2000.0f);//注:这个宽:300 是你要显示的宽度既固定的宽度,高度可以依照自己的需求而定 // if (SystemVersion_7x)//IOS 7.0 以上 // { NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil]; if (text == nil || [text isEqual:[NSNull null]]) { ch = 0; }else{ size =[text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:tdic context:nil].size; ch = size.height; } NSLog(@"高度:%ld",(long)ch); return ch; }
使用方法如下:
NSString *testString = @"123456790123456790123456790123456790123456790123456790123456790"; if ([self contentCellHeightWithText:testString] > 30) { self.messageLabelHeight.constant = [self contentCellHeightWithText:testString]; self.messageHeight.constant = self.messageHeight.constant + [self contentCellHeightWithText:testString]; }
posted on 2016-08-10 15:55 codemaker313 阅读(758) 评论(0) 编辑 收藏 举报