NSString *aString =@"真正爱上一个人的时候,一切都那么值得,包括不可避免的伤害.";
UIFont *font = [UIFont systemFontOfSize:17];
//第一种算法,ios7.0后已经废弃
CGSize titleSize = [aString sizeWithFont:font constrainedToSize:CGSizeMake(@"label的宽度", MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
//第二种算法ios7.0 后计算字符串的高度
CGRect rect = [aString boundingRectWithSize:CGSizeMake(@"label的宽度", MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil];
NSLog(@"Height:::%f",rect.size.height);
//自己封装的方法
-(CGSize)sizeWithFont:(UIFont *)font maxSize:(CGSize)maxSize string:(NSString *)string{
NSDictionary *attrs = @{NSFontAttributeName:font};
return [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
//例子
//此处1000为高度 还可以换为:MAXFLOAT
-(void)ViewDidload{
CGSizestringSize=[self sizeWithFont:font maxSize:CGSizeMake(SCREEN_WIDTH-20, 1000)string:aString];
float textH= stringSize.height;
NSLog(@"textH:::%f",textH);
}