Perhaps you could do the following with just one UILabel
per line:
Define a left word like "Coffee" and a right one like "£1.45".
Make a string by concatenating the left word with a space and the
right one.
Define the width
and height
of the frame that you want the label with that
string to be contained in, with CGSizeMake(width, height)
.
Estimate the size of that label using sizeThatFits
providing the
CGSize
constraints that you want as an argument.
If the estimated width of the label is smaller than the required
width, increase the size of your label, by adding a space to your
string and repeat.
In code:
NSArray *leftWords = @[@"Coffee", @" milk, skinny", @"Danish Pastry", @"Coca Cola", @"Full English Bfst"];
NSArray *rightWords = @[@"£1.45", @"", @"£1.75", @"£1.10", @"£12.50"];
CGFloat xOffset = 5;
CGFloat yOffset = 60;
CGFloat labelHeight = 44;
CGFloat labelWidth = 300;
for (int i = 0; i < leftWords.count; i ++) {
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(xOffset, yOffset + i * labelHeight, labelWidth, labelHeight)];
aLabel.numberOfLines = 1;
aLabel.textAlignment = NSTextAlignmentLeft;
aLabel.layer.borderColor = [UIColor greenColor].CGColor;
aLabel.layer.borderWidth = 1.0f;
NSString *leftWord = [leftWords objectAtIndex:i];
NSString *rightWord = [rightWords objectAtIndex:i];
NSMutableString *spaces = [[NSMutableString alloc] initWithString:@" "];
const CGFloat MAX_WIDTH = 310;
CGSize maxLabelSize = CGSizeMake(MAX_WIDTH, CGFLOAT_MAX);
CGSize expectedSize = CGSizeMake(0, 0);
CGFloat expectedWidth = 0.0;
NSString *phrase = @"";
do {
phrase = [NSString stringWithFormat:@"%@%@%@", leftWord, spaces, rightWord];
aLabel.text = phrase;
expectedSize = [aLabel sizeThatFits:maxLabelSize];
expectedWidth = expectedSize.width;
// Increase spaces
[spaces appendString:@" "];
} while (expectedWidth < MAX_WIDTH);
CGRect frame = aLabel.frame;
frame.size = expectedSize;
aLabel.frame = frame;
[self.view addSubview:aLabel];
}
I have placed the above within my viewDidLoad
and did #import <QuartzCore/QuartzCore.h>
to allow marking of the border of the UILabel.
Here is a screenshot of my working code:
It works for the "milk, skinny" line too as the text alignment of the label is set to NSTextAlignmentLeft
.