Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString sizeWithFont: alternative in iOS7

Tags:

ios7

The method (sizeWithFont: forWidth: lineBreakMode:) was deprecated in iOS 7.0.

But how can I do a same thing like following code in iOS 7.0?

CGSize fontSize =[self.text sizeWithFont:self.font forWidth:self.frame.size.width lineBreakMode:NSLineBreakByTruncatingTail];

Can (boundingRectWithSize:options:attributes:context:) do this? I am not sure but this is the method I searched on apple document.

Thanks for your assistance.

like image 625
user2816080 Avatar asked Dec 06 '22 05:12

user2816080


1 Answers

I have got a category for NSString to get the width or heigth of a string:

- (CGFloat)widthWithFont:(UIFont *)font
{
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
    return [[[NSAttributedString alloc] initWithString:self attributes:attributes] size].width;
}

- (CGFloat)heigthWithWidth:(CGFloat)width andFont:(UIFont *)font
{
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:self];
    [attrStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [self length])];
    CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
    return rect.size.height;
}
like image 158
matthias Avatar answered Mar 13 '23 03:03

matthias