IOS开发根据字体大小等获取文字所占的高度

时间:2022-09-01 14:18:58

Model *model = self.modelArr[indexPath.row];

//根据label文字获取CGRect
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
//set the line break mode
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;

NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:15],
NSFontAttributeName,
paragraphStyle,
NSParagraphStyleAttributeName,
nil];

//assume your maximumSize contains {250, MAXFLOAT}
CGRect lblRect = [model.text boundingRectWithSize:(CGSize){ScreenWidth - 20, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attrDict
context:nil];