NSString *str = @"UILabel自定义行间距时获取高度,UILabel自定义行间距时获取高度,UILabel自定义行间距时获取高度,UILabel自定义行间距时获取高度,UILabel自定义行间距时获取高度,UILabel自定义行间距时获取高度,UILabel自定义行间距时获取高度."; //创建tttLabel TTTAttributedLabel *tttLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(30, 55, 300, 100)]; tttLabel.lineBreakMode = NSLineBreakByCharWrapping; tttLabel.lineSpacing = 6;//设置行间距 tttLabel.font = [UIFont systemFontOfSize:12]; tttLabel.numberOfLines = 0; //设置行数为0 [tttLabel setText:str]; tttLabel.textAlignment = NSTextAlignmentLeft; tttLabel.backgroundColor = [UIColor redColor]; [self.view addSubview:tttLabel]; //获取tttLabel的高度 //先通过NSMutableAttributedString设置和上面tttLabel一样的属性,例如行间距,字体 NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:str]; //自定义str和TTTAttributedLabel一样的行间距 NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init]; [paragrapStyle setLineSpacing:6]; //设置行间距 [attrString addAttribute:NSParagraphStyleAttributeName value:paragrapStyle range:NSMakeRange(0, str.length)]; //设置字体 [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, str.length)]; //得到自定义行间距的UILabel的高度 //CGSizeMake(300,MAXFLOAt)中的300,代表是UILable控件的宽度,它和初始化TTTAttributedLabel的宽度是一样的. CGFloat height = [TTTAttributedLabel sizeThatFitsAttributedString:attrString withConstraints:CGSizeMake(300, MAXFLOAT) limitedToNumberOfLines:0].height; //重新改变tttLabel的frame高度 CGRect rect = tttLabel.frame; rect.size.height = height; tttLabel.frame = rect;
转自:http://www.cocoachina.com/ios/20150429/11724.html