简体   繁体   中英

Vertically align two labels

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

在此处输入图片说明

I tried my best, but I could only manage to create one like this. 在此处输入图片说明

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM