0

I have tried many solutions provided in stackoverflow but I can't get the correct rect of a NSAttributedString.
As an instance the solution here does not work :

CGRect paragraphRect =
  [attributedText boundingRectWithSize:CGSizeMake(300.f, CGFLOAT_MAX)
  options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
  context:nil];

Below my code :

NSMutableParagraphStyle *paragrapStyle = [[NSMutableParagraphStyle alloc] init];
paragrapStyle.alignment = NSTextAlignmentCenter;
paragrapStyle.lineHeightMultiple = 1.2;

NSMutableAttributedString *textMutableAttributedString = [[NSMutableAttributedString alloc] initWithString:textString];
[textMutableAttributedString addAttribute:NSParagraphStyleAttributeName value:paragrapStyle range:NSMakeRange(0, [textMutableAttributedString.string length])];
[textMutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:114/255. green:132/255. blue:141/255. alpha:1] range:NSMakeRange(0,[textMutableAttributedString.string length])];
[textMutableAttributedString addAttribute:NSParagraphStyleAttributeName value:paragrapStyle range:NSMakeRange(0, [textMutableAttributedString.string length])];

NSAttributedString *textAttributedString = [[NSAttributedString alloc] initWithAttributedString:textMutableAttributedString];

[text setAttributedText:textAttributedString];

CGRect textAttributedStringRect = [textAttributedString boundingRectWithSize:CGSizeMake(text.frame.size.width, CGFLOAT_MAX)
                                                                     options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                                                     context:nil];

textAttributedStringRect computed value is origin=(x=0, y=0) size=(width=260.12695, height=33.120003) while text.frame.size.width original value is 260. The computed height is completely wrong...

I have read many answers on this specific problem and none of them solve it. I hope I will have someone who knows an accurate way to calculate the rect.

Thank you for your help

16
  • floorf(textAttributedStringRect.size.width)?
    – duci9y
    Dec 9, 2013 at 17:08
  • To be sure I have replay the test with floorf. It's not a problem of CGFloat precision but rather that 33 is not even close of the correct height
    – gsempe
    Dec 9, 2013 at 17:12
  • What is the height you expect to see?
    – duci9y
    Dec 9, 2013 at 17:13
  • When I use the computed height to resize the UILabel the string is truncated. Height should be at least 20px taller
    – gsempe
    Dec 9, 2013 at 17:18
  • 2
    Using UILabel's sizeToFit method would be sufficient to resize your UILabel.
    – duci9y
    Dec 9, 2013 at 17:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.