iPhone - 根据文本调整UILabel宽度

19

如何根据文本调整标签宽度?如果文本长度较短,我希望标签宽度也小...如果文本长度较长,我希望标签宽度与文本长度相同。这是否有可能?

实际上,我有两个UIlabel。我需要将它们放在附近。但是如果第一个标签的文本太小,就会有很大的间隙。我想要消除这个间隙。


检查一下我对第二部分的答案。 - iDev
尝试使用attributedText文本。 - Vinayak
7个回答

38
//use this for custom font
CGFloat width =  [label.text sizeWithFont:[UIFont fontWithName:@"ChaparralPro-Bold" size:40 ]].width;

//use this for system font 
CGFloat width =  [label.text sizeWithFont:[UIFont systemFontOfSize:40 ]].width;

label.frame = CGRectMake(point.x, point.y, width,height);

//point.x, point.y -> origin for label;
//height -> your label height; 

12
在iOS 7.0中已经不推荐使用。 - santuxus

12

sizeWithFont:函数在iOS 7.0中已经被弃用,因此你必须使用sizeWithAttributes:函数来支持iOS 7.0+。同时为了支持老版本,可以使用以下代码:

    CGFloat width;
    if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0)
    {
        width = [text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:16.0 ]].width;
    }
    else
    {
        width = ceil([text sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:16.0]}].width);
    }

根据苹果文档建议,对 sizeWithAttributes: 方法的结果使用 ceil() 函数:

“此方法返回带小数的大小;为了将所返回的大小用于调整视图大小,必须使用 ceil 函数将其值提高到最接近的整数。”

sizeWithAttributes


老方法有什么意义呢?为什么不总是使用sizeWithAttributes? - clocksmith

5
    // In swift 2.0
    let lblDescription = UILabel(frame: CGRectMake(0, 0, 200, 20))
    lblDescription.numberOfLines = 0
    lblDescription.text = "Sample text to show its whatever may be"
    lblDescription.sizeToFit()

    // Its automatically Adjust the height

虽然这段代码片段可能解决了问题,但包括解释真的有助于提高您的帖子质量。请记住,您正在为未来的读者回答问题,而这些人可能不知道您的代码建议原因。 - Tobi Nary
1
@Vinayak Mahadev,请对这段代码片段进行一些解释。 - user23790
嗨,SmokeDispenser,只需使用lblDescription.sizeToFit(),它就会自动扩展UILabel的高度。我们不需要计算任何东西。 - Vinayak

3
尝试以下选项,
UIFont *myFont = [UIFont boldSystemFontOfSize:15.0];
// Get the width of a string ...
CGSize size = [@"Some string here" sizeWithFont:myFont];

// Get the width of a string when wrapping within a particular width
NSString *mystring = @"some strings some string some strings...";
CGSize size = [mystring sizeWithFont:myFont
                              forWidth:150.0
                lineBreakMode:UILineBreakModeWordWrap];

您可以尝试使用[label sizeToFit];方法。使用此方法,您可以将两个标签的框架设置为:
[firstLabel sizeToFit];
[secondLabel sizeToFit];
secondLabel.frame = CGRectMake(CGRectGetMaxX(firstLabel.frame), secondLabel.origin.y, secondLabel.frame.size.width, secondLabel.frame.size.height);

2

sizeWithFont constrainedToSize:lineBreakMode: 是原始的方法。以下是如何使用它的示例:

//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];   

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;

1

如果您在视图、XIB或单元格中使用约束,请使用“to”关键字。

[LBl sizeToFit];

如果它没有起作用,那么
dispatch_async(dispatch_get_main_queue(), ^{
[LBl sizeToFit];
});

在这里,更新UI主线程是关键。即使我们没有使用块,这也是一个好习惯,以确保所有更新都发生在主线程中。 - Apple_iOS0304

0
尝试以下内容:
/* Consider these two labels as the labels that you use, 
and that these labels have been initialized */

UILabel* firstLabel;
UILabel* secondLabel;

CGSize labelSize = [firstLabel.text sizeWithFont:[UIFont systemFontOfSize:12]]; 
//change the font size, or font as per your requirements

CGRect firstLabelRect = firstLabel.frame;

firstLabelRect.size.width = labelSize.width; 
//You will get the width as per the text in label

firstLabel.frame = firstLabelRect;


/* Now, let's change the frame for the second label */
CGRect secondLabelRect;

CGFloat x = firstLabelRect.origin.x;
CGFloat y = firstLabelRect.origin.y;

x = x + labelSize.width + 20; //There are some changes here.

secondLabelRect = secondLabel.frame;
secondLabelRect.origin.x = x;
secondLabelRect.origin.y = y; 

secondLabel.frame = secondLabelRect;

你遇到了什么问题? - Ravi Raman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接