Skip to content

Instantly share code, notes, and snippets.

@bentford
Created June 17, 2013 20:49
Show Gist options
  • Save bentford/5800254 to your computer and use it in GitHub Desktop.
Save bentford/5800254 to your computer and use it in GitHub Desktop.
Shows how to implement a multiline UILabel with Auto Layout. It will dynamically resize to fit whatever horizontal constraints you apply.
@interface AutoLayoutLabel : UILabel
@end
@implementation AutoLayoutLabel
{
CGFloat overrideWidth;
}
- (id)init
{
if ((self = [super init])) {
overrideWidth = 0.0f;
self.numberOfLines = 0;
self.lineBreakMode = NSLineBreakByWordWrapping;
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
// Fit the label to it's contents on rotation or text change
// http://stackoverflow.com/questions/15927086/uilabel-sizetofit-and-constraints
if (self.preferredMaxLayoutWidth != [self alignmentRectForFrame:self.frame].size.width) {
self.preferredMaxLayoutWidth = [self alignmentRectForFrame:self.frame].size.width;
[self.superview setNeedsLayout];
}
}
@end
@betzerra
Copy link

betzerra commented Sep 9, 2013

It seems that overrideWidth is not used anywhere

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