公共类.h里
/** 返回自适应高度的文本 */
+ (CGSize)sizeWithString:(NSString *)string font:(CGFloat)font maxWidth:(CGFloat)maxWidth;
/** 返回自适应宽度的文本 */
+ (CGSize)sizeWithString:(NSString *)string font:(CGFloat)font maxHeight:(CGFloat)maxHeight;
公共类.m里
/** 返回自适应高度的文本 */
+ (CGSize)sizeWithString:(NSString *)string font:(CGFloat)font maxWidth:(CGFloat)maxWidth
{
NSDictionary *attributesDict = @{NSFontAttributeName:FONT(font)};
CGSize maxSize = CGSizeMake(maxWidth, MAXFLOAT);
CGRect subviewRect = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDict context:nil];
return subviewRect.size;
}
/** 返回自适应宽度的文本 */
+ (CGSize)sizeWithString:(NSString *)string font:(CGFloat)font maxHeight:(CGFloat)maxHeight
{
NSDictionary *attributesDict = @{NSFontAttributeName:FONT(font)};
CGSize maxSize = CGSizeMake(MAXFLOAT, maxHeight);
CGRect subviewRect = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDict context:nil];
return subviewRect.size;
}
调用:(宽度是100 字体是15号 求高度)
CGSize aLabelsize = [ApplictionUtil sizeWithString:aLabel.text font:15 maxWidth:100];
aLabel.height = aLabelsize.height;