【问题标题】:UIlabel shows extra space before textUIlabel 在文本前显示额外的空间
【发布时间】:2014-02-18 07:34:42
【问题描述】:

我在我的应用程序中使用了 UILabel。它在纵向模式下正常工作。但是当我以横向模式打开我的应用程序时,它会在 UIlabel 的中心显示内容。我试过 sizeToFit 但它不起作用。只要我增加 uilabel 的宽度间距,就会开始到达 uilabel。

我的代码:

self.contentLabel.text = labeltext;
[self.contentLabel setNumberOfLines:0];
[self.contentLabel sizeToFit];

【问题讨论】:

  • 您可以显示问题的屏幕截图吗?
  • 请提供一些代码或截图
  • imgur.com/7fjlwQz,UkjCIf0 这就是我的文本在横向模式下在 uilabel 中的显示方式。
  • 标签文字已经左对齐
  • 我检查了 ny 代码 - sizeToFit 完美运行。您确定在设置新文本和更改方向后运行 sizeToFit 吗?

标签: ios device-orientation


【解决方案1】:

我怀疑您的 UILabel 本身而不是其中的文本在旋转时实际上对齐不正确。确保标签与视图顶部保持对齐。试试:

self.contentLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight;

self.contentLabel.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

编辑:另一种想法。

如果启用了自动布局并且您在viewDidLoad 中调用sizeToFit,则视图可能会在自动布局布局子视图后调整大小。请尝试将您的代码放入 viewDidLayoutSubviews

【讨论】:

  • 标签与视图顶部对齐。但内容垂直居中对齐。
  • 您确定它与顶部对齐吗?特别是在使用 sizeToFit 之后?您是否检查过边框位置,可能使用了 self.contentLabel.layer.borderWidth 和 self.contentLabel.layer.borderColor?
  • 我已经为标签使用了背景色。
  • 哦,好的。只是确保。 ;) 祝你好运!如果我想到任何其他可能的解决方案,我会告诉你的。
  • 将我的代码添加到 viewDidLayoutSubviews 工作。谢谢:)
【解决方案2】:

如果添加高度大于文本高度的 UILabel,这是正常的,并且无法更改此对齐方式(垂直居中)。

我有两个解决这个问题的方法:

使用约束:

这个大于或等于的约束很神奇。

如果您使用我建议使用的代码创建标签:

UIFont *fontReceive = [UIFont systemFontOfSize:[UIFont systemFontSize]];
CGSize sizeText = [text sizeWithFont:fontReceive constrainedToSize:CGSizeMake(260, 9999) lineBreakMode:NSLineBreakByWordWrapping];

希望这会有所帮助!

【讨论】:

  • 我认为我的字体大小有问题。因为当我使用 12 而不是 [UIFont systemFontSize] 时,它工作得很好。
【解决方案3】:

最好的解决方案是根据您要填充的文本量来更改单元格的高度。

请以下面的代码为例。

NSString *content = **YOUR_STRING_LABEL_INTENDED_CONTENT**
CGSize maximumLabelSize = CGSizeMake(390, 1000); //For example - Put in your desired label width here and maximum size etc.

NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13] forKey: NSFontAttributeName]; //This allows a calculation to be made of the space taken up, so if you're using a custom or large font it will calculate accordingly.

CGSize newExpectedLabelSize = [content boundingRectWithSize:maximumLabelSize options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size;

现在您可以使用下一行更改标签的高度,其中 label 是您创建的标签的名称。

GCRect frame = label.frame;
frame.size.height = newExpectedLabelSize.height;
label.frame = frame;

我希望这会有所帮助,干杯,吉姆。

【讨论】:

  • No visible @interface for 'NSString' 声明选择器 'boundingRectWithSize:options:attributes:context:'
  • NSString *content = 你的 labelText 是什么
  • 我创建了名为 labelContent 的字符串变量并使用了 CGSize newExpectedLabelSize = [labelContent boundingRectWithSize:maximumLabelSize options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size;