1

I want to vertically align two UILabels. One contains the description(maximum of 3 lines lines) and other contains the number.
Like this

enter image description here

I tried my best, but I could only manage to create one like this. enter image description here

BenMorel
  • 34,448
  • 50
  • 182
  • 322
smartsanja
  • 4,413
  • 9
  • 58
  • 106

2 Answers2

0

All you need to do is to change the height of the first label to fit only one line. When you do so the number will go up automatically.

Mahmoud Fayez
  • 3,398
  • 2
  • 19
  • 36
0

The following code will work:

#define kDescriptionWidth 200

...

- (void)alignNumLabel:(UILabel *)numLabel withDescriptionLabel:(UILabel *)descriptionLabel topLeftPoint:(CGPoint)topLeftPoint {
    numLabel.frame = CGRectMake(topLeftPoint.x, topLeftPoint.y, 0, 0);
    [numLabel sizeToFit];

    CGSize maxDescriptionSize = CGSizeMake(kDescriptionWidth, (descriptionLabel.numberOfLines == 0 ? CGFLOAT_MAX : descriptionLabel.font.lineHeight * descriptionLabel.numberOfLines));
    CGSize labelSize = [descriptionLabel.text sizeWithFont:descriptionLabel.font constrainedToSize:maxDescriptionSize lineBreakMode:UILineBreakModeWordWrap];
    descriptionLabel.frame = CGRectMake(CGRectGetMaxX(numLabel.frame) + 5, numLabel.frame.origin.y, labelSize.width, labelSize.height);
}

To use it, do something like:

[self alignNumLabel:numLabel withDescriptionLabel:descriptionLabel topLeftPoint:CGPointMake(10, 10)];
[self alignNumLabel:numLabel2 withDescriptionLabel:descriptionLabel2 topLeftPoint:CGPointMake(10, CGRectGetMaxY(descriptionLabel.frame) + 10)];

Let me know if you have any questions about how it works.

Ander
  • 3,688
  • 1
  • 22
  • 24
  • Thanks for the answer. I used it. but the issue is, descriptionLabel only have 1 line. (I have set descriptionLabel number of lines = 0). – smartsanja Aug 28 '12 at 06:28
  • Got it. I set descriptionLabel number of lines=2. Now it seems ok. Thanks a lot – smartsanja Aug 28 '12 at 06:31
  • The `numberOfLines` property sets the maximum number of lines, it can still be less than that if there is less text. Setting it to 0 means it can have unlimited lines and would need to be dealt with differently. In your question you stated that it would have a maximum of 3 lines, so that's why it's done that way. – Ander Aug 28 '12 at 06:33
  • Yes, I just test with number of of lines 2. Now I can change it as relevant. Thanks a lot for the answer, highly appreciated it... – smartsanja Aug 28 '12 at 06:39
  • I just made a small change to the code so it works with `descriptionLabel.numberOfLines == 0`, just in case you want to allow unlimited lines later. – Ander Aug 28 '12 at 06:44