UILabel 動態高度 Dynamic Height

UITableViewCell 有 heightForRowAtIndexPath 可以指定

但是實務上總是會碰到客戶的要求:「動態列高」

若是「想以文字內容決定 UILabel 的高度」

可以使用下面的程式

先用「文字,字型和寬度」(這點要事先決定,不然沒辦法算)計算出 UILabel 的高度

然後再用這個算出來的高度去 initWithFrame

搞定,收工放飯

 

+(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float)width {
CGSize constraint = CGSizeMake(width , 20000.0f);
CGSize title_size;
float totalHeight;

SEL selector = @selector(boundingRectWithSize:options:attributes:context:);
if ([text respondsToSelector:selector]) {
title_size = [text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName : font }
context:nil].size;

totalHeight = ceil(title_size.height);
} else {
title_size = [text sizeWithFont:font
constrainedToSize:constraint
lineBreakMode:NSLineBreakByWordWrapping];
totalHeight = title_size.height ;
}

CGFloat height = MAX(totalHeight, 40.0f);
return height;
}

This entry was posted in iOS development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *