Get correct text height for iOS 7 in iPhone SDK

2019-08-08 17:20发布

I need to get text height and grow cell's height depending upon text height which increase or decrease dynamically. I now successfully getting correct height of text for iOS 6 and prior but I am not able to get correct height iOS 7 and later. I googled and found many solution but this doesn't worked. You can see attached Image of same cell and see difference in iOS 7 text is truncating and in iOS 6 its showing correct size. I used UILabel. Follow my code of what exactly I am doing. Kindly look into it and guide me better solution if any one experienced this sort of thing earlier.

- (CGSize)getSizeOfText:(NSString *)text withFont:(UIFont *)font widthOftext:(int )txtWidth
{
CGSize boundingSize = CGSizeMake(txtWidth, 9999);
CGSize size;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
{
    CGRect textRect = [text boundingRectWithSize:boundingSize
                                         options:NSStringDrawingUsesLineFragmentOrigin
                                      attributes:@{NSFontAttributeName:font}
                                         context:nil];
    size=textRect.size;
}
else
{
    CGSize requiredSize = [text sizeWithFont:font constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
    size=requiredSize;
}

return size;
}

On iOS 6 device. iOS 6

On iOS 7 device. iOS 7

1条回答
We Are One
2楼-- · 2019-08-08 17:42

Please try this code

Declare #define kMaxHeight 1000.0f in header.

        CGSize sizeNew = [YourText sizeWithFont:[UIFont fontWithName:Fontname size:intFontSize]
                 constrainedToSize:CGSizeMake(320, kMaxHeight)
                     lineBreakMode:NSLineBreakByWordWrapping];
         txtText.numberOfLines = 0;

If you have any question let m e know.

查看更多
登录 后发表回答