http://www.cnblogs.com/shirley-1019/p/3707434.html原文地址
//
// UILabel+UILabel_StringFrame.h
// test
//
// Created by tt1 on 15/12/2.
// Copyright © 2015年 tt1. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UILabel (UILabel_StringFrame)
- (CGSize)boundingRectWithSize:(CGSize)size;
@end
.m文件
//
// UILabel+UILabel_StringFrame.m
// test
//
// Created by tt1 on 15/12/2.
// Copyright © 2015年 tt1. All rights reserved.
//
#import "UILabel+UILabel_StringFrame.h"
@implementation UILabel (UILabel_StringFrame)
- (CGSize)boundingRectWithSize:(CGSize)size
{
NSDictionary *attribute = @{NSFontAttributeName: self.font};
self.userInteractionEnabled = YES;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:5.0];//调整行间距,5是你自己想要设置的行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, self.text.length)];
self.attributedText = attributedString;
CGSize retSize = [self.text boundingRectWithSize:size
options:\
NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:attribute
context:nil].size;
return retSize;
}
@end
//自己的写的demo
l.backgroundColor=[UIColor whiteColor];
CGSize size=[l boundingRectWithSize:CGSizeMake(300, 0)];
l.numberOfLines=0;
float h=size.height/16.7;//16.7是我利用http://www.cnblogs.com/shirley-1019/p/3707434.html原文地址的那哥方法求得的高度,你先把文本写小一点求出一行的高度(前提是你的字体已经定下来了),然后利用求得总的高度来除以每行的高度。
float height=h*5+size.height;//5是我们自己设置的行间距,
l.frame=CGRectMake(10, 30, size.width , height);
[self.view addSubview:l];