Skip to content

Instantly share code, notes, and snippets.

@jellybeansoup
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jellybeansoup/b998c83f8842e742faf1 to your computer and use it in GitHub Desktop.
Save jellybeansoup/b998c83f8842e742faf1 to your computer and use it in GitHub Desktop.
Eat my shorts, auto layout.
#pragma mark - Rearrange the subviews
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
[self arrangeSubviews];
}
- (void)arrangeSubviews {
// Cover image frame
self.coverImageView.frame = CGRectMake( 15.0, 20.0, 100.0, 131.0 );
// Determine the size for the labels
CGFloat maxWidth = ( CGRectGetWidth( self.frame ) - 40.0 ) - CGRectGetWidth( self.coverImageView.frame );
CGSize titleSize = [self.titleLabel sizeThatFits:CGSizeMake( maxWidth, 100.0 )];
CGSize subtitleSize = [self.subtitleLabel sizeThatFits:CGSizeMake( maxWidth, 100.0 )];
CGSize descriptionSize = [self.descriptionLabel sizeThatFits:CGSizeMake( maxWidth, 100.0 )];
// We break after the colon if the title exceeds one line.
if( titleSize.height > 20 ) {
self.titleLabel.text = [self.titleLabel.text stringByReplacingOccurrencesOfString:@": " withString:@":\n"];
titleSize = [self.titleLabel sizeThatFits:CGSizeMake( maxWidth, 100.0 )];
}
// Update the label frames
CGFloat left = CGRectGetMaxX( self.coverImageView.frame ) + 10.0;
CGFloat spacing = 3.0;
self.titleLabel.frame = CGRectMake( left, 20.0, titleSize.width, titleSize.height );
self.subtitleLabel.frame = CGRectMake( left, CGRectGetMaxY( self.titleLabel.frame ) + spacing, subtitleSize.width, subtitleSize.height );
self.descriptionLabel.frame = CGRectMake( left, CGRectGetMaxY( self.subtitleLabel.frame ) + spacing, descriptionSize.width, descriptionSize.height );
// Figure out the total height
[super setFrame:CGRectWithHeight( self.frame, MAX( CGRectGetMaxY( self.coverImageView.frame ), CGRectGetMaxY( self.descriptionLabel.frame ) ) )];
// Re-set the colours because sometimes the get confused.
self.titleLabel.textColor = UIColor.coverHeaderTextColor;
self.subtitleLabel.textColor = UIColor.coverHeaderTextColor;
self.descriptionLabel.textColor = UIColor.coverHeaderTextColor;
}
@jellybeansoup
Copy link
Author

The code above rearranges a set of views: a UIImageView and three UILabels to match the following layout. I've highlighted labels (yellow) and the superview (purple) for clarity.

A preview of how the labels are arranged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment