Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save baphillips/6734737 to your computer and use it in GitHub Desktop.
Save baphillips/6734737 to your computer and use it in GitHub Desktop.
iOS 7 dynamic UILabel frame adjustment for a given NSString and UIFont using boundingRectWithSize:options:attributes:context:.
NSString* string = @"Hello World";
UIFont *font = [UIFont fontWithName:@"Helvetica-BoldOblique" size:21];
CGSize constraint = CGSizeMake(300,NSUIntegerMax);
NSDictionary *attributes = @{NSFontAttributeName: font};
CGRect rect = [string boundingRectWithSize:constraint
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:attributes
context:nil];
// Construct your label
UILabel* label = [[UILabel alloc] initWithFrame:rect];
[label setText:string];
[label setTextAlignment:NSTextAlignmentRight];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
[label setFont:font];
@vikipeter
Copy link

It does not work. Since lineBreakMode of label is WordWrapping, It does not give the expected result..
It Only works for CharWrapping

@fatuhoku
Copy link

fatuhoku commented Sep 1, 2015

@vikipeter is there any way that it can be made to work with WordWrapping?

@ramakanthdorai
Copy link

@fatuhoku To make it work with lineBreakMode, Add Paragraph style to the attributes

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];

CGSize size = [string boundingRectWithSize:CGSizeMake(YOUR_WIDTH , NSUIntegerMax) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{ NSForegroundColorAttributeName: [UIColor blackColor], NSFontAttributeName:[UIFont fontWithName:font size:fontSize], NSParagraphStyleAttributeName : style} context:nil].size;

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