UILabel 根据要显示的文本自动调整大小

55

我正在开发一个应用程序,在其中需要根据要显示的文本自动调整文本区域的大小。

首先,我不确定这应该使用 UILabel(在我的情况下逻辑上是显示静态文本的最佳选择),还是 UITextView

我希望如何使用它?
我想要为标签或文本视图提供文本,而不是首先定义框架,然后将文本限制在该区域内。

如果您能提供正确的解决方案,那将是非常有帮助的。

我查阅了文档和其他参考资料,但没有找到太多可帮助我解决问题的内容,或者可能是我之前已经忽略了。

10个回答

97
sizeToFit方法非常好用。 我按照以下步骤操作。
UILabel *testLabel =[[UILabel alloc] initWithFrame:CGRectMake(6,3, 262,20 )]; // RectMake(xPos,yPos,Max Width I want, is just a container value);

NSString * test=@"this is test this is test inthis is test ininthis is test inthis is test inthis is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...";

testLabel.text = test;
testLabel.numberOfLines = 0; //will wrap text in new line
[testLabel sizeToFit];

[self.view addSubview:testLabel];

15
调整视图的水平大小而非垂直大小。 - cV2
Berik的解决方案可以垂直地正确调整大小。 - Fonix

29

你可以使用以下方式查找文本大小:

CGSize textSize = [[myObject getALongText] 
                    sizeWithFont:[UIFont boldSystemFontOfSize:15] 
                    constrainedToSize:CGSizeMake(maxWidth, 2000)
                    lineBreakMode:UILineBreakModeWordWrap];

那么你可以像这样创建你的UILabel

UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,textSize.width, textSize.height];
[lbl setNumberOfLines:0];
[lbl setLineBreakMode:UILineBreakModeWordWrap];
[lbl setText:[myObject getALongText]];

2
错误:您不应该询问NSString在将其绘制到UILabel中时会有多大尺寸。 - Berik

15

在Swift中:

testLabel = UILabel(frame: CGRectMake(6, 3, 262, 20))
testLabel.text = test
testLabel.numberOfLines = 0
testLabel.sizeToFit()

在 Objective C 中

UILabel *testLabel = [[UILabel alloc] initWithFrame: CGRectMake(6, 3, 262, 20)]];
testLabel.text = test;
testLabel.numberOfLines = 0;
[testLabel sizeToFit];

9

如果你只想调整 UILabel 的高度,请使用以下方法:

@property (nonatomic, weak) IBOutlet UILabel *titleLabel;

CGRect titleLabelBounds = self.titleLabel.bounds;
titleLabelBounds.size.height = CGFLOAT_MAX;
// Change limitedToNumberOfLines to your preferred limit (0 for no limit)
CGRect minimumTextRect = [self.titleLabel textRectForBounds:titleLabelBounds limitedToNumberOfLines:2];

CGFloat titleLabelHeightDelta = minimumTextRect.size.height - self.titleLabel.frame.size.height;
CGRect titleFrame = self.titleLabel.frame;
titleFrame.size.height += titleLabelHeightDelta;
self.titleLabel.frame = titleFrame;

现在您可以使用titleLabelHeightDelta来根据标签大小布置其他视图(而无需使用自动布局)。

6

根据文本查找行数的最简单方法。您可以使用以下代码:

ceil(([aText sizeWithFont:aFont].width)/self.bounds.size.width-300); 

它返回一些浮点数值。

[lbl setNumberOfLines:floatvalue];

6
我不确定我完全理解这个问题,但是您可以在 UILabel 上使用 sizeToFit 方法(该方法从 UIView 继承)根据标签文本更改大小。

@user676298 如果有帮助,请将至少一个答案标记为答案。 - Erik Tjernlund

2

由于您将在应用程序中无数次使用此解决方案,请执行以下操作:

1)创建一个名为extensions的目录,并在其中添加一个名为UILabel.swift的新文件,其中包含以下代码:

import UIKit

extension UILabel {
    func resizeToText() {
        self.numberOfLines = 0
        self.sizeToFit()
    }
}

2) 在您的应用程序代码中,定义您想要的标签宽度,然后只需调用resizeToText()

label.frame.size.width = labelWidth
label.resizeToText()

这将在自动增加高度的同时保持宽度。

2
请注意,使用自动布局时,调用 sizeToFit 不会改变大小,因为它将在后续的自动布局计算中更改。在这种情况下,您需要为 UILabel 设置适当的高度约束,其值为“height >= xx”。

这条消息确实提供了现代自动布局技术的答案,只需仔细阅读即可。 - Ilja Popov

0

尝试下面的代码,它适用于多行

self.labelText.text = string;
self.labelText.lineBreakMode = NSLineBreakByWordWrapping;
self.labelText.numberOfLines = 0;

0

您可以使用此函数根据字符串的长度更改标签的大小

func ChangeSizeOfLabel(text:String) -> CGSize{

    let font = UIFont(name: "HelveticaNeue", size: 12)!
    let textAttributes = [NSFontAttributeName: font]
    let size = text.boundingRectWithSize(CGSizeMake(310, 999), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)
    let adjustSize = CGSizeMake(size.width, size.height)
    return adjustSize
}

并像这样使用它:

let

showLabel.frame = CGRectMake(x, y, width , self.ChangeSizeOfLabel("Hello , Height is changing dynamically.....").height)

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