Search code examples
iosuilabelnsattributedstringsizetofit

Use sizeToFit with lineSpacing


I have a UILabel with several lines. The text is set dynamically, and my label height too, with this native method :

[myLabel sizeToFit];

I have an other method that sets the line spacing in my label :

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"My long dynamic text"];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];


myLabel.attributedText = attributedString;

The problem is that even if I set the line spacing first, and then call sizeToFit, the new height of my label is to small. It doesn't take in count the line spacing.

It really is a problem as my label is in a UIScrollView and I need the right height.


Solution

  • For getting size of label dynamically based on text length use this method:

    /*! Returns the size of the label to display the text provided
        @param text
            The string to be displayed
        @param width
            The width required for displaying the string
        @param fontName
            The font name for the label
        @param fontSize
            The font size for the label
     */
    - (CGSize)getSizeForText:(NSString *)text maxWidth:(CGFloat)width font:(NSString *)fontName fontSize:(float)fontSize {
        CGSize constraintSize;
        constraintSize.height = MAXFLOAT;
        constraintSize.width = width;
        NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                              [UIFont fontWithName:fontName size:fontSize], NSFontAttributeName,
                                              nil];
    
        CGRect frame = [text boundingRectWithSize:constraintSize
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:attributesDictionary
                                          context:nil];
    
        CGSize stringSize = frame.size;
        return stringSize;
    }