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?

Alec
  • 1,646
  • 3
  • 19
  • 35

2 Answers2

0

the UILabel view does not automatically resize itself based on text. you might need to call sizeToFit every time you change the text. You also need to handle assigning the number of lines manually if want the text to wrap.

Plus, shouldn't the left label be UIViewAutoresizingFlexibleLeftMargin and vice versa? the other way around.

KDaker
  • 5,899
  • 5
  • 31
  • 44
0

Two observations:

  1. AutoresizingMasks don't expand a view based upon changes of the view's subviews, but rather on the basis of the change in the superview. That's not of interest here. It's generally more useful on things like when the superview changes dimensions as a result of orientation changes. There are other situations that you might theoretically use autoresizingMasks, but I don't think this is one of them.

  2. More logically, you could simply calculate with width of the text labels necessary to fit the desired text, and then set the UILabel's frame accordingly.

To calculate the size of the two text labels, once you set their text property, could do something like:

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];

Now that you know the size of the two labels, you can tweak the frame of the two labels, as well as their superview, accordingly.

Rob
  • 415,655
  • 72
  • 787
  • 1,044