@implementation UILabel (****)
/**
* @brief 计算文字的大小
*
* @param font 字体(默认为系统字体)
* @param height 约束高度
*/
- (CGSize)sizeWithFont:(UIFont *)font constrainedToHeight:(CGFloat)height
{
UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
CGSize textSize;
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 70000
if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = @{NSFontAttributeName: textFont,
NSParagraphStyleAttributeName: paragraph};
textSize = [self boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)
options:(NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingTruncatesLastVisibleLine)
attributes:attributes
context:nil].size;
} else {
textSize = [self sizeWithFont:textFont
constrainedToSize:CGSizeMake(CGFLOAT_MAX, height)
lineBreakMode:NSLineBreakByWordWrapping];
}
#else
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = @{NSFontAttributeName: textFont,
NSParagraphStyleAttributeName: paragraph};
textSize = [self.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)
options:(NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingTruncatesLastVisibleLine)
attributes:attributes
context:nil].size;
#endif
return CGSizeMake(ceil(textSize.width), ceil(textSize.height));
}
@end
根据高度计算文字大小
最新推荐文章于 2023-11-15 16:00:44 发布