mystic cola mystic cola - 5 months ago 26
iOS Question

Fixing deprecation with boundingRectWithSize CGRectMake

So I'm trying to fix some outstanding, pre-IOS7 deprecations involving sizeWithFont. I've been following the answers provided here 'sizeWithFont:constrainedToSize:lineBreakMode:'is deprecated:

..which mostly have to deal with CGSize and CGSizeMake. But my problem has to do with CGRectMake and I haven't quite been able to put it together the way that I want.

Here's the original code:

CGSize optimumSize = [percentageText sizeWithFont:self.percentageFont constrainedToSize:CGSizeMake(max_text_width,100)];
CGRect percFrame = CGRectMake(text_x, right_label_y, optimumSize.width, optimumSize.height);


And here's what I've tried to do:

NSString *percentageText = [NSString stringWithFormat:@"%.1f%%", component.value/total*100];
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:percentageText
attributes:@
{
NSFontAttributeName: self.percentageFont
}];
CGRect percFrame = [attributedText boundingRectWithSize:(CGRectMake(text_x, right_label_y, max_text_width,100))
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];

CGSize optimumSize = percFrame.size;


But I get the error: "Sending CGRect to parameter of incompatible type CGSize". However I need all four attributes... not just the width and height. So I have to use CGRect and not CGSize. Any idea how I can make it work?

Otherwise all of my other code that just uses CGSize works just fine. It's just I have two pieces of code that really need CGRect.

Answer

The method on NSAttributedString takes a maximum size as argument. You can set the origin you want on the CGRect it returns.

NSString *percentageText = [NSString stringWithFormat:@"%.1f%%", component.value/total*100];
            NSAttributedString *attributedText =
            [[NSAttributedString alloc]
             initWithString:percentageText
             attributes:@
             {
             NSFontAttributeName: self.percentageFont
             }];
            CGRect percFrame = [attributedText boundingRectWithSize:(CGSizeMake(max_text_width,100))
                                                            options:NSStringDrawingUsesLineFragmentOrigin
                                                            context:nil];
            percFrame.origin = CGPointMake(text_x, right_label_y)