UILabel Dynamic Width calculation Multiple Lines - ios

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.

Related

boundingRectWithSize gives height with truncated text

I am using the following method to determine the height required to display the text that i have. However i cannot get the correct height without truncating the text at the end.
CGRect labelRect = [comment boundingRectWithSize:headerMax
options:NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:#{NSFontAttributeName:font}
context:nil];
How can i say not to determine the required label height without truncating the text at the end. I want the whole text to fit into the label.
-(CGRect)getLabelSizeWithText:(NSString *)textLabel forFontSize:(CGFloat) fontSize
{
CGRect textRect;
if (textLabel != nil)
{
NSAttributedString *actualString = [[NSAttributedString alloc] initWithString:textLabel attributes:#{NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue" size:fontSize]} ];
NSStringDrawingContext *targetContext = [[NSStringDrawingContext alloc] init];
CGFloat commentLabelWidth = [[UIScreen mainScreen]bounds].size.width;
textRect = [actualString boundingRectWithSize:CGSizeMake(commentLabelWidth, 900) options:NSStringDrawingUsesLineFragmentOrigin context:targetContext];
}
return textRect;
}
This one should work. Try it
Use -
1. If you want word wrap -
labelView.lineBreakMode = NSLineBreakByWordWrapping;
labelView.numberOfLines = 2;
CGRect labelRect = [comment boundingRectWithSize:headerMax
options:NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading | NSLineBreakByWordWrapping
attributes:#{NSFontAttributeName:font}
context:nil];
2. If you Don't want truncating tail at all -
// No line break mode
labelView.numberOfLines = 0;
CGRect labelRect = [comment boundingRectWithSize:headerMax
options:NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
attributes:#{NSFontAttributeName:font}
context:nil];
Try this
 
NSString *cellText = restaurant.review;
UIFont *cellFont = [UIFont systemFontOfSize:14.0];
NSDictionary *attributes = #{NSFontAttributeName: cellFont};
CGRect labelSize = [cellText boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-20, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
I am not really sure whether I understood your question correctly; it sounds like you are trying to calculate the frame size needed to display the text and setting the frame manually with that. Additionally, by setting .numberOfLines = 2, you are limiting the text that you can show. My suggestion would be for you to set up constraints via autolayout, optionally add a .minimumScaleFactor and let it dynamically resize itself.
If you still want to calculate size, with numberOfLines taken into consideration, you can use a prototype label and have use its height
- (CGSize)preferredSizeForString:(NSString *)string
width:(CGFloat)width
{
UILabel *prototypelabel = [UILabel new];
prototypelabel.frame = CGRectMake(0, 0, width, 0);
prototypelabel.text = #"Your string";
prototypelabel.numberOfLines = 2;
[prototypelabel sizeToFit];
return prototypelabel.frame.size;
}

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;
}

Getting uilabel height for bold attributed text

My code to calculate height required to for label is as follows:
-(float)frameForText:(NSString*)text sizeWithFont:(UIFont*)font constrainedToSize: (float)width{
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
CGRect frame = [text boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options: (NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributesDictionary
context:nil];
// This contains both height and width, but we really care about height.
return frame.size.height;
}
I have called it as follows from below code to calculate height firs then used it to draw label
//form attributed title
NSString *str_title =#"This is sample title to calculate height";
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineSpacing: 2.0f];
NSDictionary *attributes = #{ NSFontAttributeName: [UIFont fontWithName:#"PTSans-Bold" size:10], NSParagraphStyleAttributeName: paragraphStyle };
NSAttributedString *attributed_title = [[NSAttributedString alloc] initWithString:str_title attributes:attributes];
//calculate height required for title
float comment_height = [self frameForText:str_title sizeWithFont:[UIFont fontWithName:#"PTSans-Bold" size:10] constrainedToSize:250];
UILabel *lbl_title;
//use calculated height here
lbl_title = [[UILabel alloc] initWithFrame:CGRectMake(60, 5, 250, title_height)];
lbl_title.numberOfLines = 0;
lbl_title.attributedText = attributed_title;
This works fine when font is "PTSans-Regular" and gives exact uilabel height. But, it is not working for "PTSans-Bold" by above code.
How should I return exact UIlabel needed to write "PTSans-Bold" text with label of width 250, font's size 10 and paragraph line spacing equal to 2? Note: the "PTSans-Bold" is not system font, it's font I have added.
Thanks.
This is easyiest way to find UILabel text height dynamically height for below iOS7
CGSize fontSize = [uilabel.text sizeWithFont:uilabel.font];
NSLog(#"height %f",fontSize.height);
for iOS7
float heightIs =[uilabel.text boundingRectWithSize:uilabel.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:#{ NSFontAttributeName:uilabel.font } context:nil].size.height;
use the below method after setting font and every properties.
- (CGFloat)getHeight:(UILabel *)label{
CGSize sizeOfText = [label.text boundingRectWithSize: CGSizeMake( self.bounds.size.width,CGFLOAT_MAX)
options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes: [NSDictionary dictionaryWithObject:label.font
forKey:NSFontAttributeName]
context: nil].size;
return sizeOfText.height;
}
OK, I solved this problem with below code:
-(float)heightOfAttrbuitedText:(NSAttributedString *)attrStr width:(CGFloat )width{
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
return rect.size.height;
}

UILabel with dynamic height into UITableviewcell

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.

how to expand the UITextview when user clicks on "more " Button in ios

There are applications with a UITextview that shows a given amount of lines and when the user clicks more it expands and shows the rest,how to add more and less button.Please give me any idea. i am new to the programming.I know how to write the code of UITextview.But i dont know how to write the code of More or less button for UITextview.Thanks in advance.
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.Change UITextView frame.size.height
CGRect frame = _textView.frame;
frame.size.height = [self getSizeWithMaxLabelSize:CGSizeMake(_textView.frame.size.height, NSIntegerMax) forTextViewWithText:_textView.text].height;
_textView.frame = frame;
3.Change subviews layout
// this will work only if you textview is on the top of other views.
[UIView animateWithDuration:0.25 animations:^{
for (UIView *subview in self.view.subviews)
subview.transform = CGAffineTransformMakeTranslation(0, _textView.frame.size.height);
}];
Should be it.

Resources