func autoLabelHeight(with text:String , labelWidth: CGFloat ,attributes : [String : Any]) -> CGFloat{
var size = CGRect()
let size2 = CGSize(width: labelWidth, height: 0)
size = text.boundingRect(with: size2, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes , context: nil);
return size.size.height
}
实例:
let contentText = "就是对雷锋精神动力大幅降低肌肤啦圣诞节放大老师家看电视了附近的伤口附近丢失哦双节快乐对方角度来说 家里的沙发经历多少附近丢失了附近丢失了几行法师看对方发 三闾大夫就是大了发动机拉萨的激发了三十分 的士力架飞机似的 附近的伤口分 风急浪大开始见风使舵两附近分 时间的浪费教室里的风景"
let attibute = [NSFontAttributeName:self.contentTextLabel.font]
let height = autoLabelHeight(with: contentText, labelWidth: SCREEN_WIDTH - 50*UIRate, attributes: attibute)
//重新对label布局
self.contentTextLabel.text = contentText
self.contentTextLabel.snp.remakeConstraints({ (make) in
make.width.equalTo(SCREEN_WIDTH - 50*UIRate)
make.height.equalTo(height)
make.centerX.equalTo(self.view)
make.top.equalTo(divideLine1).offset(11*UIRate)
})
OC版本
- (void)setupLabel {
UILabel *textLabel = [[UILabel alloc] init];
textLabel.font = [UIFont systemFontOfSize:15];
NSString *str = @"自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小自适应大小";
textLabel.text = str;
textLabel.numberOfLines = 0;
textLabel.lineBreakMode = NSLineBreakByTruncatingTail;
CGSize maximumLabelSize = CGSizeMake(300, 1000);
CGSize expectSize = [textLabel sizeThatFits:maximumLabelSize];
textLabel.frame = CGRectMake(20, 70, expectSize.width, expectSize.height);
[self.view addSubview:textLabel];