Ryan
Ryan

Reputation: 195

Centering UIImage and UILabel together

I want to center my label's text while also considering a 20x20 image that should always be just to the left of the label. Specifically, I have three labels who's text could be anything, and I want a check mark to always appear just to the left of each label - this position will vary depending on the text length though.

My best guess is making the image a subview of the label and then indenting the text but that still will be somewhat inconsistent...

Upvotes: 0

Views: 467

Answers (1)

GayleDDS
GayleDDS

Reputation: 4533

In iOS 6 you can do this with constraints and almost no code. But for iOS 5 using only springs and struts you need to manage the view frames your self. You will also need to call sizeToFit so the UILabel resizes it's self to the current text.

Here is some example code:

- (void)centerLabels
{
    CGRect viewFrame = self.view.frame;
    NSArray *allLabelsAndChecks = @[ @[self.label1, self.check1], @[self.label2, self.check2], @[self.label3, self.check3] ];

    for (NSArray *labelAndCheck in allLabelsAndChecks) {
        UILabel     *label = labelAndCheck[0];
        UIImageView *check = labelAndCheck[1];

        [label sizeToFit];

        CGRect labelFrame = label.frame;
        CGRect checkFrame = check.frame;

        CGFloat maxWidth = viewFrame.size.width - (leftMarginText + rightMargin);

        if (labelFrame.size.width > maxWidth) {
            labelFrame.origin.x   = leftMarginText;
            labelFrame.size.width = maxWidth;
            checkFrame.origin.x = leftMarginImage;
        } else {
            CGFloat slideRight = (maxWidth - labelFrame.size.width) / 2.0;
            labelFrame.origin.x = leftMarginText + slideRight;
            checkFrame.origin.x = leftMarginImage + slideRight;
        }

        label.frame = labelFrame;
        check.frame = checkFrame;
    }
}

The commplete demo project can be found here: https://github.com/GayleDDS/TestCenteredLabel.git

enter image description here

Upvotes: 1

Related Questions