使用情节提要根据文本数量垂直展开标签

Expand Label vertically based on quantity of text using Storyboard

我有一个 UIlabel 链接到一个 属性,它可以包含许多不同可能长度的文本。

如何让标签垂直扩展以容纳不同数量的文本?

我在故事板中将行设置为 0。我在 Size Inspector 中尝试了不同的高度。如果我将高度设置得足够大,就会显示第二行。但是如果只有一行,它会留下很多空白space。如果标签只有一行大小,我只会看到一行文本在标签边缘结束。

我也试过下面的代码,但没有达到预期的效果。

self.myLabel.numberOfLines = 0;
    [self.myLabel sizeToFit];

除非别无他法,否则最好不要使用自动布局。

您可以试试下面的代码。我不确定你的 UI 配置,但代码通常有效:

self.myLabel.numberOfLines = 0;
self.myLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.myLabel.text = @"your long text";
CGSize maxSize = CGSizeMake(200.0f, CGFLOAT_MAX); // you might change 200.0 to whatever suits for you

CGSize requiredSize = [self.myLabel sizeThatFits:maxSize];
//with Auto Layout you need to use: CGSize requiredSize = [self.myLabel systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

self.myLabel.frame = CGRectMake(self.myLabel.frame.origin.x, self.myLabel.frame.origin.y, requiredSize.width, requiredSize.height); //use whatever left/top you find suitable

编辑

如果您希望下面的代码按预期工作,您必须坚持使用自动调整大小而不是自动布局,因为您可能更喜欢。

下面的图片 1 显示了您必须取消选中以启用自动调整大小而不是自动布局的复选框。

那么您需要重新考虑应用于标签的自动调整蒙版。您可以设置自动调整掩码 UIViewAutoresizingFlexibleLeftMarginUIViewAutoresizingFlexibleTopMargin 以及 绝对没有别的 。请看下图2:

设置自动调整大小掩码后,在 viewcontroller class:

中创建如下方法
-(void)adjustLabelWithText:(NSString*)text {
    self.myLabel.numberOfLines = 0;
    self.myLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.myLabel.text = text;
    CGSize maxSize = CGSizeMake(self.view.bounds.size.width - 2 * self.myLabel.frame.origin.x, CGFLOAT_MAX); //I have used current window width - some margin to the both sides. you could change it to watever suitable for you
    CGSize requiredSize = [self.myLabel sizeThatFits:maxSize];
    self.myLabel.frame = CGRectMake(self.myLabel.frame.origin.x, self.myLabel.frame.origin.y, requiredSize.width, requiredSize.height);
}

并从 viewWillLayoutSubviews:

调用方法
-(void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];

    [self adjustLabelWithText:@"Chapter One\n "
     "A Stop on the Salt Route\n "
     "1000 B.C.\n "
     "As they rounded a bend in the path that ran beside the river, Lara recognized the silhouette of a fig tree atop a nearby hill. The weather was hot and the days were long. The fig tree was in full leaf, but not yet bearing fruit."]; //whatever long text you prefer
}

这将确保您获得预期的效果,而不管您可能遇到的方向变化如何。