Last active
July 26, 2018 15:26
-
-
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:.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 is there any way that it can be made to work with WordWrapping?
@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
It does not work. Since lineBreakMode of label is WordWrapping, It does not give the expected result..
It Only works for CharWrapping