Skip to content
This repository has been archived by the owner on Nov 10, 2020. It is now read-only.

UILabel自适应高度的3种方法

srxboys edited this page Jan 4, 2017 · 3 revisions
  • 第一种 -- 可以得到宽高 -- 前提一个无线大
  • 不能对富文本赋值后的计算
  • _textHeight = [label textRectForBounds:frame limitedToNumberOfLines:1].size.height;

  • 第二种 -- 可以得到宽高
  //1)确定行数,进行剪切
  //2)不确定行数,宽高一个无限大,进行剪切
  CGFloat _textHeight = 0;
  [label sizeToFit];
  _textHeight = label.frame.size.height;
  _textWidth = label.frame.size.width;

  • 第三种 对于特殊文字、字符,计算的结果并不满人意
  CGFloat _textHeight = 0;
  CGFloat width = 200;//当宽度是已知的。
  _textHeight = [label boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) 
                  options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading
                  attributes: @{NSFontAttributeName: label.font} 
                  context:nil].size.height;