【发布时间】:2010-11-04 07:54:28
【问题描述】:
在我的项目中,有一个带有文字的UILabel。字体大小为 16pt。文本内容根据不同情况而变化。我希望它可以自动调整UILabel的宽度以适应文本的总宽度而不拉伸。
有可能吗?
【问题讨论】:
标签: iphone
在我的项目中,有一个带有文字的UILabel。字体大小为 16pt。文本内容根据不同情况而变化。我希望它可以自动调整UILabel的宽度以适应文本的总宽度而不拉伸。
有可能吗?
【问题讨论】:
标签: iphone
这假设您已经设置了字体:
label.text = @"some text";
[label sizeToFit];
您还需要定义最大宽度,并告诉您的程序如果 sizeToFit 为您提供的宽度大于该最大值。
【讨论】:
sizeToFit 后检查label.frame.size.width。如果label.frame.size.width > 大于您的最大宽度,您将相应地调整大小。
这里是怎么做的,假设下面的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
【讨论】:
UILabel 的 height 时,此答案效果很好。事实上,当我看到这个页面时,这正是我所寻找的。我很乐意为您的答案投票……但它没有回答所提出的问题。尽管如此,很好的解决方案可能会帮助其他偶然发现此页面的人。
NSString *txt1=@"I am here.";
CGSize stringsize1 = [txt1 sizeWithFont:[UIFont systemFontOfSize:14]];
[label setFrame:CGRectMake(x,y,stringsize1.width,hieght)];
[label setText:txt1];
【讨论】:
我在这里看到三个选项。
首先,使标签的大小足以容纳任何文本。这是最简单的,但并不总是很好 - 取决于它周围的视图。
其次,Label 可以为较长的文本调整字体大小(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]}];
}
【讨论】:
按照这个。
CGSize stringsize = [yourString sizeWithFont:[UIFont systemFontOfSize:fontSize]];
[label setFrame:CGRectMake(x,y,stringsize.width,height)];
[label setText: yourString];
【讨论】: