如何调整和使UILabel的宽度适合文本大小?

在我的项目中,有一个带有文本的UILabel 。 字体大小是16pt。 文本内容根据不同的情况而改变。 我希望它可以自动调整UILabel的宽度,以适应文本的总宽度而不需要拉伸。

可能吗?

这假定你已经设置了字体:

 label.text = @"some text"; [label sizeToFit]; 

你还需要定义一个最大宽度,并告诉你的程序如果sizeToFit给你一个大于最大值的宽度该怎么做。

下面是如何做到这一点,假设下面的messageLabel是你想要达到预期效果的标签。 现在,试试这些简单的代码行:

  // Set width constraint for label; it's actually the width of your UILabel CGFloat constrainedWidth = 240.0f; // Calculate space for the specified string CGSize sizeOfText = [yourText sizeWithFont:yourFont constrainedToSize:CGSizeMake(constrainedWidth, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap]; UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,20,constrainedWidth,sizeOfText.height)]; messageLabel.text = yourText; messageLabel.numberOfLines = 0;// This will make the label multiline 
 NSString *txt1=@"I am here."; CGSize stringsize1 = [txt1 sizeWithFont:[UIFont systemFontOfSize:14]]; [label setFrame:CGRectMake(x,y,stringsize1.width,hieght)]; [label setText:txt1]; 

我在这里看到三个选项。

首先,让标签的尺寸足够大以容纳任何文字。 这是最简单的,但并不总是很好 – 取决于其周围的意见。

其次,标签可以调整较长文本的字体大小( adjustsFontSizeToFitWidth属性)。 这通常是不可取的,元素中的不同字体可能看起来很丑。

最后一个选项是根据当前保存的文本以编程方式调整标签的大小。 要用当前字体来计算保存文本所需的大小,请使用下面的代码:

 CGSize textSize = [[someLabel text] sizeWithFont:[someLabel font] forWidth:someLabel.bounds.size.width lineBreakMode:UILineBreakModeWordWrap]; 

如果您已经设置了字体和大小,并且已经定义了框架,请尝试使用以下两个常见条件:

 if (label.text.length > maxCharPerLine) [label setNumberOfLines:0]; // infinite lines else [label setNumberOfLines:1]; // one line only // Adjust your font size to fit your desired width. [label setAdjustsFontSizeToFitWidth:YES]; 

由于sizeWithFont在IOS 7.0折旧,那么你下面的代码

 #define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending) if (SYSTEM_VERSION_LESS_THAN(@"7.0")) { // code here for iOS 5.0,6.0 and so on CGSize fontSize = [itemCat_text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:12]]; } else { // code here for iOS 7.0 fontSize = [itemCat_text sizeWithAttributes: @{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:12]}]; } 

使用自动LayOut:

在这里输入图像说明

在ViewController上:

 override func viewDidLoad() { super.viewDidLoad() self.sampleLabel.text = "Electrical Maintenance and Repair" self.sampleLabel..sizeToFit() } 

按照这个。

 CGSize stringsize = [yourString sizeWithFont:[UIFont systemFontOfSize:fontSize]]; [label setFrame:CGRectMake(x,y,stringsize.width,height)]; [label setText: yourString];