IOS UILabel 根据内容自适应高度

时间:2021-05-31 13:50:56

iOS Label 自适应高度  适配iOS7以后的版本

更多

self.contentLabelView = [[UILabel alloc] init];

self.contentLabelView.font = SYS_FONT(15);

self.contentLabelView.lineBreakMode =NSLineBreakByTruncatingTail ;

self.contentLabelView.textColor =  [UIColor colorWithHexString:@"#444444"];

self.contentLabelView.text =[@"12312312312312321321dddsdadsadasdasdas" stringByAppendingString:@"\n\n\n\n\n\n\n"];

[self.contentLabelView setNumberOfLines:0];

//根据内容计算出label所需要的高度

  CGSize size = CGSizeMake(kScreenWidth - expectSizes.width-20, MAXFLOAT);

    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:self.contentLabelView.font,NSFontAttributeName,nil];

    CGSize  actualsize =[self.contentLabelView.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;

    self.contentLabelView.frame =CGRectMake(expectSizes.width+20, 254, actualsize.width, actualsize.height);

 

纯代码布局可能会用到,不过推荐使用xib或storyboard。