Search code examples
iosxcodeuiviewalignmentuilabel

Set UIView to resize based on UILabel


Screenshot

I'd like to have my UILabel shown here center horizontally & vertically within the overlay AND I'd like the overlay UIView (the black area with the light alpha behind the hipster lorem ipsum text) to resize to give me 10 pixels of padding at the top and bottom, but still auto-stretch its width. Can anyone please point me in the right direction? I want to make it as dynamic as I can.

Here's what I have to get it to look like this:

    descView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, 160)];
    descView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    descView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];

    descLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 600, 120)];
    descLabel.center = CGPointMake(self.view.bounds.size.width/2, descView.bounds.size.height/2);

    descLabel.backgroundColor = [UIColor clearColor];
    descLabel.opaque = NO;
    descLabel.textAlignment = UITextAlignmentCenter;

    descLabel.text = currentPhoto.desc;
    descLabel.numberOfLines = 5;

    descLabel.textColor = [UIColor whiteColor];
    descLabel.autoresizingMask = UIViewAutoresizingFlexibleMargins;

    CGRect frame = descLabel.frame;
    frame.origin.x = (descView.frame.size.width - descLabel.frame.size.width)/2;

    descLabel.frame = frame;

    [self.view addSubview:descView];
    [descView addSubview:descLabel];

Solution

  • Use https://gist.github.com/2596057 (Thats Marco Arment's subclassed UILabel)

    (or) you can use the resizeHeightToFitText method's code to do the same thing without using hte IPInsetLabel

    Once the label is sized to fit text, set your label's origin based on the height and width