TRD
TRD

Reputation: 1027

How to make height of OHAttributedLabel scale with content height?

I use an OHAttributedLabel called demoLbl for displaying text with formatted areas. This label is laid out with Interface Builder and is connected to a property in my ViewController. After setting the attributedText to the label I want all the text to be displayed in the label.
If I don't resize the label then the text is cropped at the end of the label so the rest of the text is missing.

If I use [demoLbl sizeToFit]; then the height of the label is larger or smaller in height than the text (about 10 point, varying with the text's length) thus giving me blank areas at the bottom of my view (after scrolling) plus the width of the label is increased by about 2 points.

If I calculate the height of the original text (NSString) before putting it in a NSAttributedString and adding it to the label's attributedText property then the calculated height is way too small for setting it as the label's height.

Is there a hack or trick I can apply so that the label's height is adjusted according to the NSAttributedString's height?

PS: To be more specific I wanted to add OHAttributedLabel as a tag but it's not allowed to me yet.

Upvotes: 4

Views: 2979

Answers (3)

Toni Soler
Toni Soler

Reputation: 9

I added this code to the implementation of the OHAttributedLabel class:

// Toni Soler - 02/09/2011
// Overridden of the UILabel::sizeToFit method
- (void)sizeToFit
{
    // Do not call the standard method of the UILabel class, this resizes the frame incorrectly
    //[super sizeToFit];

    CGSize constraint = CGSizeMake(self.frame.size.width, 20000.0f);
    CGRect frame = self.frame;
    frame.size = [self sizeThatFits:constraint];
    [self setFrame:frame];
}
// End Toni Soler - 02/09/2011

Thank you Olivier for sharing your code!

Upvotes: 1

AliSoftware
AliSoftware

Reputation: 32681

I'm the author of OHattributedLabel.

I made some fixes recently about my computation of the size. Please check it out it will probably solve your issue.

I also added a method named sizeConstrainedToSize:fitRange: in NSAttributedString+Attributes.h that returns the CGSize of a given NSAttributedString (quite the same way UIKit's sizeWithFont:constrainedToSize: works, but for Attributed strings and CoreText and not plain stings an UIKit) Actually OHAttributedLabel's sizeThatFits: calls this method itself now.

Upvotes: 10

Kyle Howells
Kyle Howells

Reputation: 3553

You can see if this category gives you a more reliable height. https://gist.github.com/1071565

Usage

attrLabel.frame.size.height = [attrLabel.attributedString boundingHeightForWidth:attrLabel.frame.size.width];

Upvotes: 1

Related Questions