Skip to content

Instantly share code, notes, and snippets.

@kylefox
Created January 31, 2012 00:24
Show Gist options
  • Save kylefox/1707793 to your computer and use it in GitHub Desktop.
Save kylefox/1707793 to your computer and use it in GitHub Desktop.
Create a vertically-resized, top-aligned, UILabel with padding.
// Create the _captionLabel:
_captionLabel = [[UILabel alloc] init];
_captionLabel.textColor = [UIColor colorWithRed:204 green:204 blue:204 alpha:1];
_captionLabel.backgroundColor = [UIColor clearColor];
_captionLabel.text = self.caption;
_captionLabel.numberOfLines = 0;
_captionLabel.lineBreakMode = UILineBreakModeWordWrap;
_captionLabel.font = [UIFont fontWithName:@"Helvetica" size:15];
// Calculate the frame for the caption according to a fixed width and variable size:
CGSize maxSize = CGSizeMake(300, 1000);
UIFont *captionFont = _captionLabel.font;
CGSize captionSize = [self.caption sizeWithFont:captionFont constrainedToSize:maxSize lineBreakMode:_captionLabel.lineBreakMode];
CGRect calculatedFrame = CGRectMake(10, 10, 300, captionSize.height);
_captionLabel.frame = calculatedFrame;
// Create the caption container:
_captionLabelContainer = [[UIView alloc] init];
_captionLabelContainer.backgroundColor = [UIColor colorWithRed:0 green:0 blue:100 alpha:1];
_captionLabelContainer.layer.cornerRadius = 5;
// Adjust the container's frame (padding)
calculatedFrame.size.height += 15;
calculatedFrame.size.width += 15;
_captionLabelContainer.frame = calculatedFrame;
[_captionLabelContainer addSubview:_captionLabel];
[self addSubview:_captionLabelContainer];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment