-(void)setNewFrameWithText:(NSString *)text{
CGRect frame=[selfframe];
CGFloat labelWidth=self.evalution.frame.size.width;
//最多10行,超过10行则省略
self.evalution.numberOfLines=10;
CGSize sieze=CGSizeMake(labelWidth-80,1000);
NSStringDrawingOptions option =NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading;
//NSStringDrawingTruncatesLastVisibleLine如果文本内容超出指定的矩形限制,文本将被截去并在最后一个字符后加上省略号。如果指定了NSStringDrawingUsesLineFragmentOrigin选项,则该选项被忽略 NSStringDrawingUsesFontLeading计算行高时使用行间距。(字体大小+行间距=行高)
NSDictionary *attributes = [NSDictionarydictionaryWithObject:self.evalution.fontforKey:NSFontAttributeName];
CGRect rect2 = [textboundingRectWithSize:sieze
options:option
attributes:attributes
context:nil];
frame.size.height=rect2.size.height+40;
self.evalution.text=[textstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]];
self.frame=frame;
[self.evalutionsetInsets:UIEdgeInsetsMake(0,5,0,0)];
}
//与上面差不多的效果
//调整高度
-(void)setIntroductionText:(NSString*)text withHeight:(NSInteger)reduceHeight{
if ([textisKindOfClass:[NSNullclass]]) {
return;
}
if ([textisKindOfClass:[NSStringclass]]&&![textisKindOfClass:[NSNullclass]]) {
//获得当前cell高度
CGRect frame = [selfframe];
CGFloat labelWidth=self.frame.size.width-100;
//设置label的最大行数
self.messageLabel.numberOfLines =10;
// CGSize size = CGSizeMake(labelWidth-100, 1000);
CGSize size =CGSizeMake(labelWidth-reduceHeight,1000);
CGSize labelSize = [textsizeWithFont:[UIFontsystemFontOfSize:t_1]constrainedToSize:sizelineBreakMode:NSLineBreakByClipping];
self.messageLabel.frame =CGRectMake(self.messageLabel.frame.origin.x,self.messageLabel.frame.origin.y, labelSize.width, labelSize.height);
//计算出自适应的高度
frame.size.height = labelSize.height+40;
self.frame = frame;
//文本赋值
self.messageLabel.text = [textstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]];
}
else
return;
}
// 根据文字计算label的高度
CGSize maxSize =CGSizeMake(self.placehoderLabel.width,MAXFLOAT);
CGSize placehoderSize = [self.placehodersizeWithFont:self.placehoderLabel.fontconstrainedToSize:maxSize];
self.placehoderLabel.height = placehoderSize.height;
在返回高度的代理方法中调用上面的方法获得高度,即可成功设置高度
最后一种方法,label自适应高度:
//设置预期高度,设置 row 自动高度
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
//返回自动高度
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
//设置 label 不换行lbl.numberOfLines = 0
lbl.adjustsFontSizeToFitWidth = true
PS:自适应控件在拉约束的时候,不要设置固定高度。