Exact height of NSTextContainer - ios

I have a method used to calculate the exact height size for a text container. The method returns not correct values when trying to measure the height of an attributed string filled with arabic html content.
This is the code used :
- (CGFloat)textViewHeightForAttributedText:(NSAttributedString *)text andWidth:(CGFloat)width
{
NSTextStorage *textStorager = [[NSTextStorage alloc] initWithAttributedString:text];
NSTextContainer *textContainerr = [[NSTextContainer alloc] init];
textContainerr.size = CGSizeMake(width, FLT_MAX);
NSLayoutManager *layoutManagerr = [[NSLayoutManager alloc] init];
[layoutManagerr addTextContainer:textContainerr];
[textStorager addLayoutManager:layoutManagerr];
[textStorager addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:self.fontSize] range:NSMakeRange(0, [textStorager length])];
[textContainerr setLineFragmentPadding:5.0];
layoutManagerr.allowsNonContiguousLayout = NO;
CGFloat size = [layoutManagerr usedRectForTextContainer:textContainerr].size.height;
NSLog(#"size: %f - height_TextView:%f",size,height_TextView);
return size;
}
Is there any solution for measuring the exact height of any html content ?
Thanks

Related

Wrong bounding rect for right aligned text in UILabel

- (CGRect)boundingRectForGlyphRange:(NSRange)glyphRange inTextContainer:(NSTextContainer *)container;
returns wrong rect for glyph range when attributed text is right aligned in UILabel. How to fix this please ?
Code to calculate the bounding rect of attributed text when tapped on UILabel (textAlignment set to right in UILabel)
- (void)tap:(UITapGestureRecognizer *)recognizer {
UILabel *label = (UILabel *)recognizer.view;
CGSize labelSize = recognizer.view.bounds.size;
NSTextContainer *container = [[NSTextContainer alloc] initWithSize:labelSize];
container.lineFragmentPadding = 0.0;
container.lineBreakMode = label.lineBreakMode;
container.maximumNumberOfLines = label.numberOfLines;
NSLayoutManager *manager = [NSLayoutManager new];
[manager addTextContainer:container];
NSTextStorage *storage = [[NSTextStorage alloc] initWithAttributedString:label.attributedText];
[storage addLayoutManager:manager];
CGPoint touchPoint = [recognizer locationInView:label];
NSInteger indexOfCharacter = [manager characterIndexForPoint:touchPoint
inTextContainer:container
fractionOfDistanceBetweenInsertionPoints:nil];
NSRange range = NSMakeRange(indexOfCharacter, 1);
NSRange glyphRange;
[manager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange];
CGRect rect = [manager boundingRectForGlyphRange:glyphRange inTextContainer:container];
}
The problem is that you are setting the label's text and textAlignment, and then pulling out the label's attributedText and handing it to the text kit stack, in the belief that it magically translates your label configuration into an attributed string. It doesn't!
If you want right-aligned text that the text kit stack can see as right-aligned, set your label's attributedText only, endowing it with features such as a right-aligned paragraph style.
Solved this!!
The problem was the label was made to be right aligned using textAlignment property of UILabel. As mentioned in comments label.attributedText doesn't know anything about it.
Instead add text alignment using NSParagraphStyleAttributeName as :
NSMutableAttributedString *mutableString = [NSMutableAttributedString new];
//Add to your string
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setAlignment:NSTextAlignmentRight];
[mutableString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, mutableString.length)];
label.attributedText = mutableString;

Height of attributedText not returned

I need to display text in UITableViewCell and need to set the height of tableView. I am using the below methods to calculate the height of row dynamically. But the height is coming out to be a lot more than the actual height.
+ (CGFloat)getquestionLabelHeight:(NSNumber *)width text:(NSString *)text {
CGSize constraint = CGSizeMake([width floatValue], CGFLOAT_MAX);
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [[ZUtility getAttributedText:text].string boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:[UIFont fontWithName:#"OpenSans" size:14]} context:context].size;
return boundingBox.height;
}
The reason I am converting text to attributed text is because normal text has html content and for line breaks '&nbsp' is present.
+(NSAttributedString *)getAttributedText:(NSString *)text {
NSMutableAttributedString *attrHTMLText = [[[NSAttributedString alloc] initWithData:[text dataUsingEncoding:NSUTF8StringEncoding] options:#{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: #(NSUTF8StringEncoding)} documentAttributes:nil error:nil] mutableCopy];
[attrHTMLText addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"OpenSans" size:14.0] range:NSMakeRange(0, attrHTMLText.length)];
[attrHTMLText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, attrHTMLText.length)];
return attrHTMLText;
}
For width 343, height is coming out to be 915 which is not accurate.
You can use boundingRectWithSize
NSAttributedString *attrStr = [[NSAttributedString alloc]initWithString:#"<p>The HTML <strong><strong></strong> element defines <strong>strong</strong>text, with added semantic importance.</p>"];
// your attributed string
CGFloat width = 200; // whatever your desired width is
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];;
NSLog(#"%#",NSStringFromCGRect(rect));

How to know if the word within UILabel was cut

I try to develop autoshrink functionality. I have attributed text, set into a fix-size UILabel. After that I lower the font size and check if the text fits to given container size.
Problem is that UILabel ignores NSLineBreakByWordWrapping if a word is longer than container width. Resulting in I have cut tail word.
Here is the code:
- (void) setCardText:(NSString *)txt {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:txt];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
[paragraphStyle setAlignment:NSTextAlignmentCenter];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [txt length])];
self.cardLabel.attributedText = attributedString;
for (CGFloat fontSize = 40; fontSize >=5; fontSize--) {
[self.cardLabel setFont:[UIFont fontWithName:#"GothamPro-Light" size:fontSize]];
[paragraphStyle setLineSpacing:fontSize*0.3f];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [txt length])];
self.cardLabel.lineBreakMode = NSLineBreakByWordWrapping;
[self.cardLabel sizeToFit];
if (self.cardLabel.frame.size.width <= 220) {
[self.cardLabel setFrame:CGRectMake(40, 40, 220, self.cardLabel.frame.size.height)];
}
if (self.cardLabel.frame.size.height <= 210) {
[self.cardLabel setFrame:CGRectMake(40, 40, self.cardLabel.frame.size.width, 210)];
}
if (self.cardLabel.frame.size.width <= 220 && self.cardLabel.frame.size.height <= 210) {
[self.cardLabel setFrame:CGRectMake(40, 40, 220, 210)];
break;
}
};
And here is the result (I'm sorry for screenshot in Russian): http://take.ms/kg2mG
In the third line the word is cut and its ending is moved to the next line.
I guess it happens because initially this word doesn't fit to container width and was forcibly broken in half. I suppose I need sort of cut-word-detector, which tells me to keep lowering font size. Or another guess is to oblige the UILabel to be expanded by “unfit word”. But I can't find anything that does this job.
Also I can explode given string into words and check if every single of them fits to container width. But I think this method is a wheel inventing. Is there something I missed that can easily solve my issue?
The method sizeToFit calls sizeThatFits: which returns the ‘best’ size to fit the current bounds and then resize label. So at first you constrain the label and it has to fit the given width. You can see description of NSLineBreakByWordWrapping - Wrapping occurs at word boundaries, unless the word itself doesn’t fit on a single line.
For your purposes you should allow label to fit the knowingly more wider width than it requires. But it is difficult because the task is to find the best font size and we cannot predict the width. And the best way is to find font size based on the longest word in the text.
So the algorithm:
Detect the longest word, by separating by spaces.
Iteratively, decrease the font size and calculate the size of the longest word while the word is bigger than required width.
Set calculated font to full text and call sizeThatFits.
Please, find the sample code below ("Verdana" font was used for testing)
- (void) setText {
NSString * text = #"Incidental, indirect, secondary, side rival - Побочный, косвенный, второстепенный, боковой соперник";
CGFloat maxWidth = 300.;
[self setText:text toLabel:self.label maxWidth:maxWidth];
}
- (void) setText:(NSString *)text
toLabel:(UILabel*)label
maxWidth:(CGFloat)maxWidth
{
CGFloat fontSize = [self fontSizeOfWord:[self theLongestWord:text]
initialFontSize:40.
constrainedByWidth:maxWidth];
NSMutableAttributedString * attributedString = [self attributedStringForText:text];
[self setupAttributedStirng:attributedString withFontWithSize:fontSize];
label.attributedText = attributedString;
CGRect labelFrame = label.frame;
labelFrame.size = [label sizeThatFits:[attributedString sizeAdaptedForWidth:maxWidth]];
label.frame = labelFrame;
}
- (NSString*) theLongestWord:(NSString*)text {
NSArray * words = [text componentsSeparatedByString:#" "];
NSUInteger longestLength = 0;
NSUInteger index = NSNotFound;
for(int i = 0; i < words.count; i++) {
NSString * word = words[i];
CGFloat length = word.length;
if(length > longestLength) {
longestLength = length;
index = i;
}
}
return (index != NSNotFound ? words[index] : nil);
}
- (CGFloat)fontSizeOfWord:(NSString *)word
initialFontSize:(CGFloat)initialFontSize
constrainedByWidth:(CGFloat)maxWidth
{
NSMutableAttributedString * wordString = [self attributedStringForText:word];
CGFloat fontSize = initialFontSize;
for (; fontSize >= 5.; --fontSize) {
[self setupAttributedStirng:wordString
withFontWithSize:fontSize];
CGSize wordSize = [wordString sizeAdaptedForWidth:CGFLOAT_MAX];
if(wordSize.width <= maxWidth){
break;
}
}
return fontSize;
}
- (NSMutableAttributedString*) attributedStringForText:(NSString*)text {
return (text&&text.length ? [[NSMutableAttributedString alloc] initWithString:text]:nil);
}
- (void)setupAttributedStirng:(NSMutableAttributedString *)attributedString
withFontWithSize:(CGFloat)fontSize
{
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
[paragraphStyle setAlignment:NSTextAlignmentCenter];
UIFont * font = [UIFont fontWithName:#"Verdana" size:fontSize];
[paragraphStyle setLineSpacing:fontSize*0.3f];
NSDictionary * attributes = #{NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: font};
[attributedString addAttributes:attributes
range:NSMakeRange(0, [attributedString length])];
}
Category for NSAttributedString:
#implementation NSAttributedString (AdaptedSize)
- (CGSize) sizeAdaptedForWidth:(CGFloat)width
{
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self);
CGSize targetSize = CGSizeMake(width, CGFLOAT_MAX);
CGSize fitSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter,
CFRangeMake(0, [self length]),
NULL, targetSize, NULL);
CFRelease(framesetter);
return fitSize;
}
#end
Have you tried the UILabel.adjustsFontSizeToWidth property?

Setting dynamic UILabel Height

I have an app with a table view that needs to support dynamic cell heights. In the cell's layoutSubviews method, I am generating a frame for my UILabel controls, which are the only dynamic sized controls in the cells.
For some reason, the width being returned from the following method is less than what it should be and the text gets truncated, but only on short text, such as one word. The width should be maintained as the width that is passed in as the initial frame.
That said, what my method needs to accomplish is adjusting the size of the label to fit all the text while maintaining a preset width.
Here's the code I am using:
- (CGRect)getLabelSizeForText:(NSString*)text withInitialRect:(CGRect)labelFrame andFontSize:(CGFloat)fontSize{
CGSize constrainedSize = CGSizeMake(labelFrame.size.width, MAXFLOAT);
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize], NSFontAttributeName, nil];
CGSize requiredSize = [text boundingRectWithSize:constrainedSize
options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
attributes:attributesDict context:nil].size;
CGRect adjustedFrameRect = CGRectMake(labelFrame.origin.x, labelFrame.origin.y, requiredSize.width, requiredSize.height);
return adjustedFrameRect;
}
This works for me,
+ (CGSize)textSizeForText:(NSString *)text {
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat width = screenWidth - kPaddingRight;
CGSize maxSize = CGSizeMake(width, CGFLOAT_MAX);
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 2.5;
NSDictionary *dict = #{NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName: [UIFont systemFontOfSize:15] };
[attributedString addAttributes:dict range:NSMakeRange(0, text.length)];
CGRect paragraphRect = [attributedString boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];
return paragraphRect.size;
}

How to set max height and fixed width for UITextView and force ellipsis rather than scroll if overflow occurs?

Here's my goal:
I want to use a UITextView rather than a UILabel because I want users to be able to select text and copy.
I want the UITextView to max out at a height of 60 points.
I want the UITextView to have a fixed width of 300 points.
I want the UITextView to line break on words.
Let's say, based on the attributed text string I feed it, that it takes 3 lines to reach the 60 point max height. Therefore, if I feed the UITextView 6 lines worth of attributed text I want the UITextView to max out at 60 points and display 3 lines followed by an ellipsis (e.g. ...).
I don't want the text view to ever be scrollable.
If I feed the UITextView a single word as attributed text, such as "Hello", I want the UITextView to still have a fixed width of 300 points but a dynamic height that scales to as small as it can be, approximately 20 points for a single line of text in this example.
I want the UITextView to have zero internal padding.
Any ideas?
- (CGFloat)textViewHeightForAttributedText:(NSAttributedString*)text andWidth:(CGFloat)width
{
UITextView *calculationView = [[UITextView alloc] init];
[calculationView setAttributedText:text];
CGSize size = [calculationView sizeThatFits:CGSizeMake(width, FLT_MAX)];
return size.height;
}
- (void)viewDidLoad
{
// Invoke super
[super viewDidLoad];
// Get text of unknown length
NSMutableAttributedString *myAttributedString = [[NSMutableAttributedString alloc] initWithString:#"String of unknown length here..." attributes:#{NSForegroundColorAttributeName : [UIColor redColor]}];
// Get ellipsis w/ matching attributes
NSDictionary *endCharAttributes = [myAttributedString attributesAtIndex:myAttributedString.length - 1 effectiveRange:NULL];
NSAttributedString *ellipsis = [[NSAttributedString alloc] initWithString:#"..." attributes:endCharAttributes];
// Define size constraints
CGFloat maxHeight = 60;
CGFloat fixedWidth = 300;
// Get starting height
CGFloat textViewHeight = [self textViewHeightForAttributedText:myAttributedString andWidth:fixedWidth];
// Reduce string size and add ellipsis until we fit within our height constraint
while (textViewHeight > maxHeight)
{
NSLog(#"%f", textViewHeight);
NSRange substringRange = {0, myAttributedString.length - 6}; // Reducing by 6 works for my app (strings are never huge)
myAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[myAttributedString attributedSubstringFromRange:substringRange]];
[myAttributedString appendAttributedString:ellipsis];
NSLog(#"myAttributedString = %#", myAttributedString);
textViewHeight = [self textViewHeightForAttributedText:myAttributedString andWidth:fixedWidth];
}
// Init and config UITextView
UITextView *textView = [[UITextView alloc] init];
textView.attributedText = myAttributedString;
textView.frame = CGRectMake(0, 0, fixedWidth, textViewHeight);
[self.view addSubview:textView];
}
Have a more elegant solution? Post it!
UPDATE: You can increase the performance of - (CGFloat)textViewHeightForAttributedText:(NSAttributedString*)text andWidth:(CGFloat)width by adding a helpers class and implementing the the following class methods:
// Private, gets us to alloc init calculation view one time for life of application
+ (UITextView *)calculationView
{
static UITextView *_calculationView;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_calculationView = [[UITextView alloc] init];
});
return _calculationView;
}
// Public, app calls this a lot
+ (CGFloat)textViewHeightForAttributedText:(NSAttributedString*)text andWidth:(CGFloat)width usingUIEdgeInset:(UIEdgeInsets)edgeInsets
{
[self calculationView].textContainerInset = edgeInsets;
[self calculationView].attributedText = text;
CGSize size = [[self calculationView] sizeThatFits:CGSizeMake(width, FLT_MAX)];
return size.height;
}
Have you considered subclassing UILabel and adding the capability to select and copy text? Mattt Thompson has a good example here.
My solution is
- (NSString*)stringByTruncatingToWidth:(CGFloat)width maxHeight:(CGFloat)maxHeight font:(UIFont *)font;
{
NSString *ellipsis = #"…";
NSMutableString *truncatedString = [self mutableCopy];
if ([self textSizeForMaxWidth:width font:font].height > maxHeight)
{
truncatedString = [[truncatedString stringByAppendingString:ellipsis] mutableCopy];
NSRange range = {truncatedString.length - 4, 1};
[truncatedString deleteCharactersInRange:range];
while ([truncatedString textSizeForMaxWidth:width font:font].height > maxHeight){
[truncatedString deleteCharactersInRange:range];
range.location--;
}
}
return truncatedString;
}
And help method for calculating text size for max width
- (CGSize)textSizeForMaxWidth:(CGFloat)width font:(UIFont *)font
{
NSTextStorage *textStorage = [[NSTextStorage alloc]
initWithString:self];
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize: CGSizeMake(width, MAXFLOAT)];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
[textStorage addAttribute:NSFontAttributeName value:font
range:NSMakeRange(0, [textStorage length])];
[textContainer setLineFragmentPadding:0.0];
[layoutManager glyphRangeForTextContainer:textContainer];
CGRect frame = [layoutManager usedRectForTextContainer:textContainer];
return frame.size;
}

Resources