Mady Mady - 4 months ago 7x
iOS Question

Dynamically getting height of UILabel according to Text return different Value for iOS 7.0 and iOS 6.1

I am using the this method for getting the height of the UILabel Dynamically:

+(CGSize) GetSizeOfLabelForGivenText:(UILabel*)label Font:(UIFont*)fontForLabel Size: (CGSize)LabelSize{
label.numberOfLines = 0;
CGSize labelSize = [label.text sizeWithFont:fontForLabel constrainedToSize:LabelSize lineBreakMode:NSLineBreakByCharWrapping];
return (labelSize);

With this solution I am getting the exact size of UILabel if my code is running on below iOS 7
but if I run my application on iOS7 then it is returns a different value.


Basically you have to dynamically set frame.Like below:

//Compatible for both ios6 and ios7.  

CGSize constrainedSize = CGSizeMake(self.resizableLable.frame.size.width  , 9999);

NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                      [UIFont fontWithName:@"HelveticaNeue" size:11.0], NSFontAttributeName,

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"textToShow" attributes:attributesDictionary];

CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

if (requiredHeight.size.width > self.resizableLable.frame.size.width) {
    requiredHeight = CGRectMake(0,0, self.resizableLable.frame.size.width, requiredHeight.size.height);
CGRect newFrame = self.resizableLable.frame;
newFrame.size.height = requiredHeight.size.height;
self.resizableLable.frame = newFrame;