Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically resize label in iOS 7

In iOS 6, I am using :

CGSize labelSize = [self.text sizeWithFont:self.font constrainedToSize:size lineBreakMode:self.lineBreakMode];
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y , labelSize.width, self.frame.size.height);

To dynamically resize a UILabel. This does not work in iOS 7 so I tried:

NSString *text = self.text;
CGFloat width = size.width;
UIFont *font = self.font;
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text
                                                                 attributes:@{ NSFontAttributeName: font }];

CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                              options:NSStringDrawingUsesDeviceMetrics
                              context:nil];
CGSize size = rect.size;

self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y , size.width, self.frame.size.height);

This is inside a category on UILabel, but this is not working also... Any ideas what I should be using?

like image 570
user426132 Avatar asked Dec 11 '22 11:12

user426132


1 Answers

Try something like this (working without auto-layout) :

NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                                           [UIFont fontWithName:@"FontName" size:15], NSFontAttributeName,
                                                            nil];

CGRect frame = [label.text boundingRectWithSize:CGSizeMake(263, 2000.0)
                                                     options:NSStringDrawingUsesLineFragmentOrigin
                                                  attributes:attributesDictionary
                                                     context:nil];

CGSize size = frame.size;
like image 83
Jordan Montel Avatar answered Jan 15 '23 18:01

Jordan Montel