调整UILabel的大小以适应字体大小和文本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了调整UILabel的大小以适应字体大小和文本相关的知识,希望对你有一定的参考价值。

This code will resize a UILabel so that the label is as small as it can be in both width and height, based on the text in it and the font used.
  1. frame = CGRectMake(160, labelTitle2.frame.origin.y + labelTitle2.frame.size.height + 136, 270, 25);
  2. UILabel *labelContent3 = [[UILabel alloc] initWithFrame: frame];
  3. labelContent3.text = @"click here.";
  4. labelContent3.textColor = UIColorFromRGB(0x606060);
  5. labelContent3.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:13];
  6. labelContent3.backgroundColor = [UIColor clearColor];
  7. labelContent3.textAlignment = UITextAlignmentLeft;
  8. labelContent3.numberOfLines = 0;
  9. maximumLabelSize = CGSizeMake(270,9999);
  10. expectedLabelSize = [labelContent3.text sizeWithFont:labelContent3.font
  11. constrainedToSize:maximumLabelSize
  12. lineBreakMode:labelContent3.lineBreakMode];
  13. newFrame = labelContent3.frame;
  14. newFrame.size.height = expectedLabelSize.height;
  15. labelContent3.frame = newFrame;
  16. [cell.contentView addSubview:labelContent3];
  17. [labelContent3 release];

以上是关于调整UILabel的大小以适应字体大小和文本的主要内容,如果未能解决你的问题,请参考以下文章

调整UILabel的大小以适应Word Wrap

为啥在 Interface Builder 中更改字体大小会阻止 UILabel 调整大小以适应内容?

调整字体大小以适应边界矩形?

调整 UILabel 字体大小以适合文本

将字体大小调整为 uilabel 宽度

自动调整 UILabel 文本大小以适应 UILabel 宽度