Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 245
TRD Avatar asked Dec 17 '22 12:12

TRD


2 Answers

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.

like image 69
AliSoftware Avatar answered Jan 18 '23 23:01

AliSoftware


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];
like image 43
Kyle Howells Avatar answered Jan 18 '23 22:01

Kyle Howells