1.新建一个字符串的类别
#import NSString (Extension)
- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize;
@end
@implementation NSString (Extension)
#pragma mark 计算字符串大小
- (CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize
{
NSDictionary *dict = @{NSFontAttributeName: font};
CGSize textSize = [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
return textSize;
}
2.如何使用
NSString *tempStr = @"《肖申克的救赎》里有一句台词:刚入狱的时候,你痛恨周围的高墙;慢慢地,你习惯了生活在其中;最终你会发现自己不得不依靠它而生存。这就叫体制化";
//(控件宽度)
CGFloat textW = txtWidth;
//文字高度
CGFloat textH = [txtAnswers sizeWithFont:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(textW, MAXFLOAT)].height;
//最后设置numberOfLines = 0;