UILabel with dynamic height into UITableviewcell - ios

I am developing an app which required to display UILabel into UITableviewCell. I also need to resize UILabel as per text size.
I am using following code for get contentsize of text size.
CGRect rect = [as boundingRectWithSize:CGSizeMake(220.0, 2000.0) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName: font} context:nil];
For update frame of UILabel I use following code.
rect.origin.x = cell.lblDescription.frame.origin.x;
rect.origin.y = cell.lblDescription.frame.origin.y;
rect.size.width = cell.lblDescription.frame.size.width;
[cell.lblDescription setFrame:rect];
It set wrong frame.
Please find attached screenshot.

NSString *text = [NSString stringWithFormat:#"%#",[[arr_cart objectAtIndex:indexPath.row] objectForKey:#"name"]];
UIFont *font = [UIFont fontWithName:#"ArialMT" size:12];
CGSize size = [(text ? text : #"") sizeWithFont:font constrainedToSize:CGSizeMake(200, 9999) lineBreakMode:NSLineBreakByWordWrapping];
UILabel *lbl_desc=[[UILabel alloc]init];
lbl_desc.numberOfLines = 0;
lbl_desc.frame=CGRectMake(70,18, size.width, size.height);
lbl_desc.lineBreakMode = NSLineBreakByWordWrapping;
lbl_desc.text = (text ? text : #"");
lbl_desc.font = font;
lbl_desc.backgroundColor=[UIColor clearColor];
lbl_desc.textColor = [UIColor darkTextColor];
[cell.contentView addSubview:lbl_desc];
[lbl_desc release];

You have to check the height of the label in - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath UITableViewDelegate Method.
CGSize maximumLabelSize = CGSizeMake(your_label_width, FLT_MAX);
CGSize expectedLabelSize = [label_text sizeWithFont:[UIFont fontWithName:#"your_font" size:your_font_size] constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
then set the cell height as expectedLabelSize.height.
also do the same thing in your custom cell.

Use following code
[self setDynamicHeightOfLabel:lblName withLblWidth:97 andFontSize:13];
In above method you just need to pass your UILabel name with specific width and fontSize of label.
-(void) setDynamicHeightOfLabel:(UILabel *) myLabel withLblWidth:(CGFloat) width andFontSize:(int) fontSize
{
CGSize myLabelSize = CGSizeMake(width, FLT_MAX);
CGSize expecteingmyLabelSize = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:myLabelSize lineBreakMode:myLabel.lineBreakMode];
CGRect lblFrame = myLabel.frame;
lblFrame.size.height = expecteingmyLabelSize.height;
myLabel.frame = lblFrame;
int addressLine = myLabel.frame.size.height/fontSize;
myLabel.numberOfLines = addressLine;
}
Using above code you can set dynamic height of UILabel.

Related

Why is the height of UITableViewCell is smaller than the height of its text?

I have a UITableView with UITableViewCells, I set the height of each cell in the function heightForRowAtIndexPath in the fallowing way:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
NSStringDrawingOptions opts = (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading);
CGSize boundingRect = CGSizeMake(450.f, CGFLOAT_MAX);
CGSize size = [cell.detailTextLabel.text boundingRectWithSize:boundingRect
options:opts
attributes:[cell.detailTextLabel.attributedText attributesAtIndex:0 effectiveRange:nil]
context:nil].size;
CGFloat height = size.height;
size = [cell.textLabel.text boundingRectWithSize:boundingRect
options:opts
attributes:[cell.textLabel.attributedText attributesAtIndex:0 effectiveRange:nil]
context:nil].size;
height += size.height;
return height;
}
But the cell that I get is too small for the text, and longer text doesn't fit:
The text that is written in cell is set in the following way:
NSString *nickName = #"some nickname"; // gets the nickname
NSString title = [NSString stringWithFormat:#"%# wrote:", nickName];
NSString *detail = #"some text"; // gets the content of the message
[cell.textLabel setText: title];
[cell.detailTextLabel setText: detail];
cell.detailTextLabel.numberOfLines = 0;
cell.detailTextLabel.lineBreakMode = NSLineBreakByWordWrapping;
Why is the height of the cell too short?
From method boundingRectWithSize:options:attributes:context:
https://developer.apple.com/reference/foundation/nsstring/1524729-boundingrectwithsize :
"This method returns the actual bounds of the glyphs in the string"
What is missing is the margins of the cell, which can be accessed with cell.layoutMargins:
height += cell.layoutMargins.top + cell.layoutMargins.bottom;
Try with the boundingRect method of NSAttributedString (Swift 3)
//change this value with the width of your UITableViewCell
let availableWidth:CGFloat = 355
let stringBoundingRect = NSAttributedString(string: "your string").boundingRect(with: CGSize(width: availableWidth, height: CGFloat.greatestFiniteMagnitude), options: [.usesDeviceMetrics, .usesLineFragmentOrigin], context: nil)
let height = stringBoundingRect.height
In Objective-C:
// change this value with the width of your UITableViewCell
CGFloat availableWidth = 355;
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:#"your string"];
CGRect stringBoundingRect = [attrStr boundingRectWithSize:CGSizeMake(availableWidth, CGFLOAT_MAX) options: NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesDeviceMetrics context:nil];
CGFloat height = stringBoundingRect.size.height;

UITextView add ...more button at the end of visible text

UITextView add ...more button at the end of visible text like on facebook.
I am sorry if it already mentioned somewhere. Specifically I am interested how to count position of the end of visible text with wrapping words
1 . Check UItextView size base on text and Font:
// return the size for UITextView for both IOS7 and IOS6
-(CGSize) getSizeWithMaxLabelSize:(CGSize) maxLabelSize forTextViewWithText:(NSString *) text
{
CGSize expectedLabelSize;
CGSize maximumLabelSize = maxLabelSize;
if (SYSTEM_VERSION_GREATER_THAN(#"6.2")) {
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont fontWithName:#"Arial" size:EPCommentViewFontSize] forKey: NSFontAttributeName];
CGRect rect =[text boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil];
expectedLabelSize = rect.size;
expectedLabelSize.height = ceilf(expectedLabelSize.height);
expectedLabelSize.width = ceilf(expectedLabelSize.width);
} else {
expectedLabelSize = [text sizeWithFont:[UIFont fontWithName:#"Arial" size:EPCommentViewFontSize] constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
}
return expectedLabelSize;
}
2 . Compare your UITextView height with expectedLabelSize.height to show ViewMore or not
3 . Change UITextView frame.size.height when touched viewMore
CGRect frame = _textView.frame;
frame.size.height = [self getSizeWithMaxLabelSize:CGSizeMake(_textView.frame.size.height, NSIntegerMax) forTextViewWithText:_textView.text].height;
_textView.frame = frame;

UILabel Dynamic Width calculation Multiple Lines

I have UILabel where i have 2 lines of text. I used the below code to calculate the dynamic width and height
CGSize expectedLabelSize = [[aLabel text] sizeWithFont:aLabel.font
constrainedToSize:aLabel.frame.size
lineBreakMode:aLabel.lineBreakMode];
CGRect rect = [aLabel frame];
rect.size.width = expectedLabelSize.width;
[aLabel setFrame:rect];
Now if there is multiple lines in the UILabel how can i detect the width. See the image for more clearence.
set property for Label
label.numberOfLines = 0;
CGFloat labelHeight= [self heightOfLabelWithIngredientLine:pixers.name];
[label setFrame:CGRectMake(10,10,100,labelHeight)];
- (CGFloat)heightOfLabelWithIngredientLine:(NSString *)stringLabel
{
CGRect frame;
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:#"Helvetica" size:14.0f], NSFontAttributeName, nil];
frame = [stringLabel boundingRectWithSize:CGSizeMake(20.0f, 999.0f) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributesDictionary context:nil];
return frame.size.height;
}
Customize your label properties in
- (CGFloat)heightOfLabelWithIngredientLine:(NSString *)stringLabel
method.

iOS auto adjust label height

I'm using the following code to auto adjust the height of a label in a UITableView. It works the majority of the time, but certain times text is cut off. Is there something wrong with my code, or anything else I need to add?
UILabel *textLabel = ((UILabel *)[cell viewWithTag:3]);
textLabel.text = text;
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [text sizeWithFont:textLabel.font constrainedToSize:maximumLabelSize lineBreakMode:textLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = textLabel.frame;
newFrame.size.height = expectedLabelSize.height;
textLabel.frame = newFrame;
In iOS 7 sizeWithFont: constrainedToSize: lineBreakMode: is deprecated, now you should use:
CGSize maxSize = CGSizeMake(296.f, FLT_MAX);
CGRect labRect = [someText boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:textLabel.font} context:nil];
textLabel.frame = CGRectMake(0, 0, maxSize.width, labRect.size.height);
textLabel.text = someText;

UILabel won't adjust height to fit content

I can't get this dynamic label to resize its height according to the content. It logs the correct info but the label is always the same height. Any ideas?
self.descriptionLabel.text = string;
self.descriptionLabel.adjustsFontSizeToFitWidth = YES;
self.descriptionLabel.numberOfLines=0;
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [string sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14] constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
//adjust the label the the new height.
CGRect newFrame = self.descriptionLabel.frame;
newFrame.size.height = expectedLabelSize.height;
NSLog(#"the height %f", newFrame.size.height);
self.descriptionLabel.frame = newFrame;
CGSize constraintSize = CGSizeMake(requiredWidth, MAXFLOAT);
CGSize labelSize = [requiredLableText sizeWithFont:requiredFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
returned size will give u the dynamic height of the UILabel

Resources