How to make OHAttributedLabel scale height with content height?

I am using an OHAttributedLabel called demoLbl to display text with formatted areas. This shortcut is laid out using Interface Builder and connected to a property in my ViewController. After the attribitedText attribute is assigned to the label, I want all the text to appear on the label.
If I do not resize the label, then the text is cut off at the end of the label so that the rest of the text is missing.

If I use [demoLbl sizeToFit]; then the height of the mark is greater or less than the text (about 10 points, changing with the length of the text), thereby giving me empty areas at the bottom of my view (after scrolling) plus the width of the mark is increased by about 2 points.

If I calculate the height of the source text (NSString) before putting it in the NSAttributedString and adding it to the attribitedText property, then the calculated height is too small to set it as the height of the label.

Is there a way to hack or trick that can be applied so that the height of the inscription is adjusted to the height of the NSAttributedString?

PS: To be more specific, I wanted to add OHAttributedLabel as a tag, but this is not allowed to me yet.

+4
source share
3 answers

I am the author of OHattributedLabel.

I recently made some corrections about my size calculation. Please check this will probably solve your problem.

I also added a method called sizeConstrainedToSize:fitRange: to NSAttributedString+Attributes.h that returns CGSize for the given NSAttributedString (UIKit sizeWithFont:constrainedToSize: works exactly the sizeWithFont:constrainedToSize: , but for attribute strings and CoreText, not for simple UIKit bites) Actually sizeThatFits: now calls this method.

+10
source

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

Using

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

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 Olivier for sharing the code!

+1
source

All Articles