0

I have a UIView which contains two UILabel objects, which are populated programmatically. I want the left UILabel to be right-aligned, and the right UILabel to be left-aligned. This is my pretty ASCII representation:

 ___________________
|  ______   ______  |
| |  ASDF| |ASDF  | |
| |______| |______| |
|___________________|

I have tried all sorts of masks and alignment properties to no avail. Here is what I thought the correct solution would be, so perhaps someone can point out the flaw in my understanding.

The container UIView needs UIViewAutoResizingFlexibleWidth so that it can expand to fit labels with variable widths. Both the left and the right UILabel need UIViewAutoResizingFlexibleWidth so that they expand to fit content with variable width. The left UILabel needs UIViewAutoresizingFlexibleRightMargin so that the left margin remains fixed. The right UILabel needs UIViewAutoresizingFlexibleLeftMargin so that the right margin remains fixed.

Conceptual problem with this implementation:

  • As the texts expand, they could just expand over each other as that would still fit the container

I am having the overlap problem, as well as the right margin does not seem to be fixed like it is supposed to, rather there is just a large gap on the right side.

Does anyone know what might be a solution?

4

2 回答 2

0

UILabel视图不会根据文本自动调整自身大小。sizeToFit每次更改文本时,您可能都需要致电。如果希望文本换行,您还需要手动分配行数。

另外,不应该是左标签UIViewAutoresizingFlexibleLeftMargin,反之亦然?另一种方式。

于 2012-07-03T22:05:07.303 回答
0

两个观察:

  1. AutoresizingMasks 不会根据视图子视图的变化来扩展视图,而是根据父视图的变化来扩展视图。这里不感兴趣。当超级视图由于方向变化而改变尺寸时,它通常更有用。在其他情况下,理论上您可能会使用 autoresizingMasks,但我认为这不是其中之一。

  2. 更合乎逻辑的是,您可以简单地计算适合所需文本所需的文本标签的宽度,然后相应地设置 UILabel 的框架。

要计算两个文本标签的大小,一旦设置了它们的 text 属性,可以执行以下操作:

CGSize leftSize  = [leftLabel.text  sizeWithFont:leftLabel.font  forWidth:self.view.frame.size.width lineBreakMode:UILineBreakModeWordWrap];
CGSize rightSize = [rightLabel.text sizeWithFont:rightLabel.font forWidth:self.view.frame.size.width lineBreakMode:UILineBreakModeWordWrap];

现在您知道两个标签的大小,您可以相应地调整两个标签的框架以及它们的超级视图。

于 2012-07-03T22:27:58.553 回答