Use sizeToFit with lineSpacing - ios

I have a UILabel with several lines. The text is set dynamically, and my label height too, with this native method :
[myLabel sizeToFit];
I have an other method that sets the line spacing in my label :
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:#"My long dynamic text"];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:5];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
myLabel.attributedText = attributedString;
The problem is that even if I set the line spacing first, and then call sizeToFit, the new height of my label is to small. It doesn't take in count the line spacing.
It really is a problem as my label is in a UIScrollView and I need the right height.

For getting size of label dynamically based on text length use this method:
/*! Returns the size of the label to display the text provided
#param text
The string to be displayed
#param width
The width required for displaying the string
#param fontName
The font name for the label
#param fontSize
The font size for the label
*/
- (CGSize)getSizeForText:(NSString *)text maxWidth:(CGFloat)width font:(NSString *)fontName fontSize:(float)fontSize {
CGSize constraintSize;
constraintSize.height = MAXFLOAT;
constraintSize.width = width;
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:fontName size:fontSize], NSFontAttributeName,
nil];
CGRect frame = [text boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize stringSize = frame.size;
return stringSize;
}

Try using – boundingRectWithSize:options:context: method of the NSMutableAttributedString. Refer the Apple Docs for more info.

Related

Calculate height and number of lines of the label

I have a text that is shown in a UILabel. However, this text have several line spaces as shown below. Now, I want to calculate the height of this label, considering the newline, Bold-text and font size. Since this text can not be placed in a Single line in the label, there might be several lines that we must determine at runtime. Based on this height I want to increase the y cordinate of my UILabel so the UILabel will always be stuck to the bottom of the screen. (Only the height will increase (upwards))
How can I solve this?
NSAttributedString *linespace = [[NSAttributedString alloc] initWithString: #"\n"];
NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc]initWithString:#"Mathews is a " attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:40]}];
NSAttributedString* attributed = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:#"%#", #"Bad guy"] attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:40]}];
[mutableString appendAttributedString: linespace];
[mutableString appendAttributedString: attributed];
[mutableString appendAttributedString: linespace];
You can get height by
CGRect rectCountry = [mutableString boundingRectWithSize:(CGSize){#“YOUR WIDTH”, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize sizeCountry = rectCountry.size;

UILabel with multiple chained NSAttributedString, with line limit, show the tail truncation with NSBackgroundColorAttributeName of unseen text

The dots are added automatically by the UILabel, cause of line limitation, but they get the background color of hidden truncated text:
So I have UILabel with line limit of 10 and line break mode of TruncatingTail.
I also have 2 types of attributed strings that build this UILabel content.
NSForegroundColorAttributeName, NSFontAttributeName
NSBackgroundColorAttributeName, NSForegroundColorAttributeName, NSFontAttributeName
Any idea why the UILabel is adding background color to the dots? There is text in line 12 (which is truncated) that have that background...
=Here Given Code Try it..
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:#"test"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = NSLineBreakByTruncatingTail;
[text addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, text.length)];
label.attributedText = text;
It looks like your NSAttributedString styling is picking up on an instance of "Windsor" that is past the truncation point.
You could find where the truncation occurs, and then only apply the text attribute to the range of the string up to the truncation point.
See this SO answer to calculate this range.
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.lineBreakMode = mylabel.lineBreakMode;
NSDictionary *attributes = #{NSFontAttributeName : mylabel.font,
NSParagraphStyleAttributeName : paragraph};
CGSize constrainedSize = CGSizeMake(mylabel.bounds.size.width, NSIntegerMax);
CGRect rect = [mylabel.text boundingRectWithSize:constrainedSize
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:attributes context:nil];
if (rect.size.height > mylabel.bounds.size.height) {
NSLog(#"TOO MUCH");
}

How to set correctly the line height of UILabel with an AttributedString?

I have a UILabel which uses an Attributed String. I want to have its line height to be exactly the size of the font size, not a pixel bigger. However, a top and bottom padding are being added. See image below:
This is my code to create the label.
NSDictionary *basicAttributes = #{NSForegroundColorAttributeName: [UIColor whiteColor], NSBackgroundColorAttributeName: [UIColor blueColor]};
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:basicAttributes];
UIFont *font = [UIFont fontWithName:#"AvenirNext-Regular" size:20.0];
[attributes setObject:font forKey:NSFontAttributeName];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineHeightMultiple = 1.0f;
[attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
self.helloWorldLabel.attributedText = [[NSMutableAttributedString alloc] initWithString:#"Hola" attributes:attributes];
Attempts
I have tried to call sizeToFit after setting the attributedText without success.
[self.helloWorldLabel sizeToFit];
I have played with other attributes of NSMutableParagraphStyle such as lineSpacing without success.
paragraphStyle.lineSpacing = 0.0f;
What am I missing?
Thanks in advanced
It sounds like you want to use boundingRectWithSize: Here's a short example of how to use it. This code will dynamically determine your label size based on the text in your label. Setting the constraining sizes allows a max size if content needs to overflow to multiple lines.
NSString *text = [NSString stringWithFormat:#"Title Header:%#", value];
NSRange boldRange = [text rangeOfString:#"Title Header:"];
NSRange normalRange = [text rangeOfString:value];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
//Add attributes for appropriate ranges
[attributedText setAttributes:#{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue-Bold" size:13.0f]} range:boldRange];
[attributedText setAttributes:#{ NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue" size:13.0f]} range:normalRange];
//Determine rect for attributed text constrained within max values
CGRect textAttributedSize = [attributedText boundingRectWithSize:CGSizeMake(CellTitleWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:NULL];
[self.myLabel setText:attributedText];
[self.myLabel setFrame:textAttributedSize];
Check this link. There is no 100% way to correctly set the frame to fit the letters. You can calculate the attributed string with CoreText like using CTFramesetterRef CTFramesetterSuggestFrameSizeWithConstraints but it is more additional work.

Setting attributedText of UILabel causing issue with Lengthier content

In my project I want to add an attributed text in UILabel placed on the xib.
It's working perfectly, but if large text appears it shows some issues.
My current implementation:
- (void)viewDidLoad
{
[super viewDidLoad];
_demoLabel.numberOfLines = 0;
_demoLabel.lineBreakMode = NSLineBreakByWordWrapping;
_demoLabel.attributedText = [self demoNameWithFontSize:21 andColor:[UIColor redColor]];
}
- (NSMutableAttributedString *)demoNameWithFontSize:(CGFloat)fontSize andColor:(UIColor *)color
{
NSMutableAttributedString *attributedText = nil;
NSString *demoName = #"Blah blah blah";
UIFont *demoFont = [UIFont fontWithName:#"Zapfino" size:fontSize];
attributedText = [[NSMutableAttributedString alloc] initWithString:demoName];
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.lineBreakMode = NSLineBreakByWordWrapping;
[attributedText addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, [demoName length])];
[attributedText addAttribute:NSFontAttributeName value:demoFont range:NSMakeRange(0, [demoName length])];
[attributedText addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, [demoName length])];
return attributedText;
}
Output:
Issue:
It is not displaying the whole text, even if I applied the NSMutableParagraphStyle.
How can I solve this ?
Alternative I found:
If I change
UIFont *demoFont = [UIFont fontWithName:#"Zapfino" size:fontSize];
to
UIFont *demoFont = [UIFont systemFontOfSize:fontSize];
It'll work and gives output like:
But the issue is I need to use custom font, can't use default font. Also cannot change the font size.
I checked UILabel class reference and googled, but couldn't find a solution. Please help me.
Is there anyway to span this text into multiple lines ?
You need to resize the UILabel to fit the text.
You can calculate the size with the boundingRectWithSize:options:context: NSAttributedString class method, which takes an attributed string and calculates the size within a set rect based on all the attributes of the string.

ios Dynamic sizing labels

I've tried to search online, but haven't found a clear answer for my issue so I've come to ask for your expert advice. I have a view with 2 labels on it. The first label is used to show an abbreviation of a name, 2-3 letters. and the second label shows the full name.
The question that I have is if there was a way to dynamically size the label based on the font type, size, and string length given? I ask because I would like the second label close to the first without too much empty space between the two or without the first label overlapping the second.
The reason that this isn't all in one label is because the first label should have a bigger font and different color scheme then the second label.
Any advice is greatly appreciated.
You can calculate the size of in which your string will appear and then can set frame of your UILabel to that size see following code as a sample -
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
Update -
Use sizeWithAttributes: instead, which now takes an NSDictionary. Pass in the pair with key UITextAttributeFont and your font object like this:
CGSize size = [string sizeWithAttributes:
#{NSFontAttributeName:
[UIFont systemFontOfSize:17.0f]}];
Check Replacement for deprecated sizeWithFont: in iOS 7? for more details
This will also do the trick and will take into account attributed text
label.attributedText = attrString;
CGSize maximumLabelSize = CGSizeMake(187,CGFLOAT_MAX);
CGSize requiredSize = [label sizeThatFits:maximumLabelSize];
CGRect labelFrame = label.frame;
labelFrame.size.height = requiredSize.height;
label.frame = labelFrame;
'sizeWithFont:' is deprecated: first deprecated in iOS 7.0.
so try sizeWithAttributes
- (void)viewDidLoad
{
[super viewDidLoad];
label = [[UILabel alloc] initWithFrame:CGRectMake(20, 40, 300, 20)];
label.backgroundColor = [UIColor blueColor];
const CGFloat fontSize = 30;
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
UIColor *foregroundColor = [UIColor blackColor];
attrs = [NSDictionary dictionaryWithObjectsAndKeys:
regularFont, NSFontAttributeName,
foregroundColor, NSForegroundColorAttributeName
, nil];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]
initWithString:#"Test Text"
attributes:attrs];
[label setAttributedText:attributedText];
[self.view addSubview:label];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CGSize expectedLabelSize = [label.text sizeWithAttributes:attrs]; // iOS 7 Code <--
CGRect newFrame = label.frame;
newFrame.size.width = expectedLabelSize.width;
label.frame = newFrame;
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]
initWithString:#"Longer Test Text"
attributes:attrs];
[label setAttributedText:attributedText];
}
As sizeWithFont: is deprecated in iOS 7, you need to use sizeWithAttributes (as maver explained here). In order to simplify code, you can add a method that you can reuse like this:
-(CGRect)rectForText:(NSString *)text
usingFont:(UIFont *)font
boundedBySize:(CGSize)maxSize
{
NSAttributedString *attrString =
[[NSAttributedString alloc] initWithString:text
attributes:#{ NSFontAttributeName:font}];
return [attrString boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
}
And make use of it
CGSize maximumLabelSize = CGSizeMake(280,9999);
UIFont *font = [UIFont systemFontOfSize:20];
CGRect titleRect = [self rectForText:post.title // <- your text here
usingFont:font
boundedBySize:maximumLabelSize];
In addition of Saurabh's answer. I had the same problem and you should add this line [yourLabel setNumberOfLines:0]; in order the whole text to be shown in X lines.

Resources