How to calculate TextView height base on text - ios

I am using the code below for calculate the height of text, then set this height for UILabel and UITextView
CGSize targetSize = CGSizeMake(300, CGFLOAT_MAX);
NSString *message = #"The Internet connection appears to be offline.";
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [message boundingRectWithSize:targetSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:FontOpenSanWithSize(14)}
context:context].size;
CGSize size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
// it will return size:width = 299 and size height 20
// => if I use this height and set for UILabel, it can display full content
// => if I use this height and set for UITextView, it can not display full content
It's work perfect for UILabel but for UITextView sometime it calculate wrong.
I think the problem happened because the padding (left, right) of UITextView is bigger than UILabel.
So how can I calculate the correct size of text for display in UITextView. Any help or suggestion would be great appreciated.
Like the description image below
With the same size (300), same font, same text but the UITextView display in 2 lines, but UILabel in 1 lines.
And my code for calculate height return 20, it not enough for display in 2 lines, so the UITextViewcan not display full content
The reason why I need to calculate the height of UITextView base on text because my UITextView is in a popup.
And the popup height will depend on the TextView height

There are two things you can try:
Set textView.textContainerInset = UIEdgeInsetsZero
Set textView.textContainer.lineFragmentPadding = 0
With these operations you can get rid of all the padding in the textView and when its width matches with the label's one the heights are also the same.
Here's a sample code you can place in an empty viewController and test it yourself:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSString *text = #"The internet connection appears to be offline.";
CGFloat width = 100.f;
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 20, width, 300)];
textView.font = [UIFont fontWithName:#"AvenirNext-Regular" size:12.f];
textView.text = text;
[self.view addSubview:textView];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20 + width, 20, width, 300)];
label.numberOfLines = 0;
label.font = [UIFont fontWithName:#"AvenirNext-Regular" size:12.f];
label.text = text;
[self.view addSubview:label];
// Getting rid of textView's padding
textView.textContainerInset = UIEdgeInsetsZero;
textView.textContainer.lineFragmentPadding = 0;
// Setting height of textView to its contentSize.height
CGRect textViewFrame = textView.frame;
textViewFrame.size = textView.contentSize;
textView.frame = textViewFrame;
// Setting height of label accorting to it contents and width
CGRect labelFrame = label.frame;
labelFrame.size = [label sizeThatFits:CGSizeMake(width, HUGE_VALF)];
labelFrame.size.width = width;
label.frame = labelFrame;
NSLog(#"Label bounds: %#", NSStringFromCGRect(label.bounds));
NSLog(#"TextView bounds: %#", NSStringFromCGRect(textView.bounds));
// Visualizing final effect with borders
textView.layer.borderColor = [UIColor redColor].CGColor;
textView.layer.borderWidth = 1.f;
label.layer.borderColor = [UIColor greenColor].CGColor;
label.layer.borderWidth = 1.f;
}
Console output:
2016-09-01 14:29:06.118 stack39268477[943:243243] Label bounds: {{0, 0}, {100, 66}}
2016-09-01 14:29:06.119 stack39268477[943:243243] TextView bounds: {{0, 0}, {100, 66}}

You don't need to calculate Height of UITextview based on text.
Just change frame and set height like this:
textview.size.height = textview.contentSize.height;
This is easy solution. I hope this helps you.

This calculates the size of any string, whether or not you put them in a text view.
let frame = NSString(string: yourText).boundingRect(
with: CGSize(width: yourDesiredWidth, height: .infinity),
options: [.usesFontLeading, .usesLineFragmentOrigin],
attributes: [.font : yourFont],
context: nil)
let height = frame.size.height

Most of the answers here are hints into the right direction :-)
So, just to sum it all up...
UITextView uses a NSTextContainer (inside a private API _UITextContainerView) to do the real layout work.
This NSTextContainer(View) may have insets to the surrounding UITextView, which are set by UITextView's textContainerInset property.
The defaults for this insets seem to be:
top: 8
left: 0
bottom: 8
right: 0
The NSTextContainer itself may have additional left and right insets for the text itself. These insets are set in NSTextContainer's lineFragmentPadding property.
The default for this is 5.0.
As a result, when calculating the optimum frame size for a UITextView based on the boundingRect for some text inside that UITextView, we have to take all these insets into account:
CGSize reservedSpace = CGSizeMake((textView.textContainerInset.left + (2.0 * textView.textContainer.lineFragmentPadding) + textView.textContainerInset.right),
(textView.textContainerInset.top + textView.textContainerInset.bottom));
CGSize targetSize = CGSizeMake((300.0 - reservedSpace.width), CGFLOAT_MAX);
NSString* message = #"The Internet connection appears to be offline.";
NSStringDrawingContext* context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [message boundingRectWithSize:targetSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:FontOpenSanWithSize(14)}
context:context].size;
CGSize size = CGSizeMake(ceil(boundingBox.width),
(ceil(boundingBox.height) + reservedSpace.height));
Good luck :-)

Swift 5
A classic hack I've used to do this is create a function that takes the String as a parameter. Within the function it generates a label with the width required, infinite number of lines, and a height of "too much". Then apply sizeToFit() on the label and return the height of the frame.
func calculatedHeight(for text: String, width: CGFloat) -> CGFloat {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: width,
height: .greatestFiniteMagnitude))
label.numberOfLines = 0
label.text = text
label.sizeToFit()
return label.frame.height
}
The returned height can be applied to a UITextField height anchor. Though I do recommend calculating the width dynamically based on screen size, but that's up to you.

self.textView.textContainerInset = UIEdgeInsets.zero
self.textView.textContainer.lineFragmentPadding = 0
In storyboard or xib mark textview height >=0.
If you are using text view with table view.
Calculate cell height according to content, textview will adjust it's space.

Related

How to programmatically sizeToFit width AND height on UILabel?

I'm programmatically creating multi-line UILabels ([label setNumberOfLines:0];).
The built-in sizeToFit method of UILabel works great for 1 line UILabels, but for multi-line text, it sets the height properly, but the width is set too small, causing longer text lines to wrap.
I don't know the label width until after the user enters their text. I want to resize the labels to fit the width of the longest line of text. And per #DonMag's comment, I also want to restrict the label to not be wider than the screen.
I tried different lineBreakMode settings but there isn't a 'nowrap' option.
I've searched SO and there are many related solutions but none that solve the problem of sizeToFit for both width and height.
Is there a way to programmatically size a multi-line UILabel to fit BOTH the width AND the height of the text?
You can do this with boundingRectWithSize...
Add your label to the view and give it a starting width constraint (doesn't really matter what value, as it will be changed).
Keep a reference to that width constraint (IBOutlet works fine if you're using IB).
Don't give it a height constraint.
When you set the text of the label, you can use this to change its width:
// get the font of the label
UIFont *theFont = _theLabel.font;
// get the text of the label
NSString *theString = _theLabel.text;
// calculate the bounding rect, limiting the width to the width of the view
CGRect r = [theString boundingRectWithSize:CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName: theFont}
context:nil];
// change the constant of the constraint to the calculated width
_theWidthConstraint.constant = ceil(r.size.width);
// NOTE: If you are *not* using auto-layout,
// this same calculation can be used to explicitly set
// the .frame of the label.
Edit:
As per the OP's requirement, a complete, runnable example -- using code only, no storyboards / IB -- can be found here: https://github.com/DonMag/MultilineLabelFitWidth
Edit 2:
GitHub project updated... now includes examples for both manual frame setting and auto layout / constraints.
With some more experimentation, I found something that does the trick that I have not seen in SO (yet...). In general it works like this:
Find the longest text line
Set numberOfLines to 1 (temporarily)
Set label text to longest text line
Call label.sizeToFit (sets label width for longest line)
Set numberOfLines to 0 (multi-line)
Set label text to full multi-line text
Call label.sizeToFit (sets label height for all lines)
Voila! Now your UILabel is sized to fit your multi-line text.
Here is an example (demo project on GitHub: UILabelSizeToFitDemo):
- (UILabel *)label = nil;
- (void)updateLabel:(NSString *)notes {
// close to the "sticky" notes color
UIColor *bananaColor = [ViewController colorWithHexString:#"#FFFC79"];
if (_label == nil) {
_label = [[UILabel alloc] init];
_label.numberOfLines = 0;
_label.textColor = UIColor.blackColor;
[_label setBackgroundColor:[bananaColor colorWithAlphaComponent:0.9f]];
_label.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:_label];
}
// make font size based on screen size
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
CGFloat fontSize = MIN(screenWidth,screenHeight) / 12;
[_label setFont:[UIFont systemFontOfSize:fontSize]];
// split lines
NSArray *lines = [notes componentsSeparatedByString:#"\n"];
NSString *longestLine = lines[0]; // prime it with 1st line
// fill a temp UILabel with each line to find the longest line
for (int i = 0; i < lines.count; i++) {
NSString *line = (NSString *)lines[i];
if (longestLine == nil || line.length > longestLine.length) {
longestLine = line;
}
}
// force UILabel to fit the largest line
[_label setNumberOfLines:1];
[_label setText:longestLine];
[_label sizeToFit];
// make sure it doesn't go off the screen
if (_label.frame.size.width > screenWidth) {
CGRect frame = _label.frame;
frame.size.width = screenWidth - 20;
_label.frame = frame;
}
// now fill with the actual notes (this saves the previous width)
[_label setNumberOfLines:0];
[_label setText:notes];
[_label sizeToFit];
// center the label in my view
CGPoint center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
[_label setCenter:center];
}
UPDATE: Here is an alternate complete solution, using the boundinRectWithSize from the code snippet by #DonMag:
-(void)updateLabel:(NSString *)notes {
// close to the "sticky" notes color
UIColor *bananaColor = [ViewController colorWithHexString:#"#FFFC79"];
if (_label == nil) {
_label = [[UILabel alloc] init];
_label.numberOfLines = 0;
_label.textColor = UIColor.blackColor;
_label.backgroundColor = [bananaColor colorWithAlphaComponent:0.9f];
_label.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:_label];
}
// set new text
_label.text = notes;
// make font size based on screen size
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
CGFloat fontSize = MIN(screenWidth,screenHeight) / 12;
[_label setFont:[UIFont systemFontOfSize:fontSize]];
// calculate the bounding rect, limiting the width to the width of the view
CGRect frame = [notes boundingRectWithSize:CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName: _label.font}
context:nil];
// set frame and then use sizeToFit
[_label setFrame:frame];
[_label sizeToFit];
// center the label in my view
CGPoint center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
[_label setCenter:center];
}

How to get UITextView height according to content in iOS 9

I'm using a UITextView to display some data. I need to calculate the height of the UITextView depending on its content. I have tried contentSize.height, but it doesn't work for me.
Does anyone have a solution for this?
Here is my code with AutoLayout. I have set the height constraint with outlet
CGFloat height= _myTextView.contentSize.height;
_heightConstraint.constant = height;
You could use the following to work out the height of the text, works perfectly for me:
CGSize maximumTextViewSize = CGSizeMake(textView.frame.size.width, CGFLOAT_MAX);
NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin;
NSDictionary *attr = #{NSFontAttributeName: [your font and font size]};
CGRect textViewBounds = [theText boundingRectWithSize:maximumTextViewSize
options:options
attributes:attr
context:nil];
CGFloat height = ceilf(textViewBounds.size.height);
Just add
[self layoutIfNeeded]
After you've calculated the height, and you should be alright.
If not, come back to me.
func heightForView(text:String, font:UIFont, width:CGFloat, xpos:CGFloat) -> CGFloat {
let label:UILabel = UILabel(frame: CGRectMake(xpos, 0, width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
First size the text view to the content with:
[yourtTextView sizetofit];
Then get the height of the view with:
double textViewHeight = yourtTextView .frame.size.height;
The textView is not aware of its content when the text view scroll is enabeld
change that in the storyboard by unchecking the Scrolling enables or by code by adding this:
textview.scrollEnabled = false
this will make the textView aware of its content and it will grow or shrink in height based on its content.

Dynamically adding multiline label in a view

I am dynamically creating UILabel in my app to display a list of directions for a recipe. The labels populate correctly displaying all the items one after another.
The problem is when the text goes on next line of the label, it is overlapped with the next label.
I have set numberOfLines to 0 and also set lineBreakMode to NSLineBreakByWordWrapping. This helps the label to display text on multiple lines.
I have tried to adjust the height of the label, as you will see in the code, but it doesn't work.
How do I prevent the overlapping of labels due to multiline text in label?
Here is the code for populating the labels with multilines:
//add all the directions to the uiview
for (int i = 0; i < self.recipe.directions.count; i++)
{
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0,(i+1)*25,280,25)];
label.lineBreakMode = NSLineBreakByWordWrapping; //multiple lines in a label
label.numberOfLines = 0;
label.text =[NSString stringWithFormat: #"%#", self.recipe.directions[i]];
[label sizeToFit]; // resize the width and height to fit the text
NSLog(#"Actual height is: %f", label.frame.size.height); // Use this for spacing any further elements
CGSize expectedLabelSize = [label.text sizeWithFont:label.font
constrainedToSize:label.frame.size
lineBreakMode:NSLineBreakByWordWrapping];
//adjust the label the the new height.
CGRect newFrame = label.frame;
newFrame.size.height = expectedLabelSize.height;
label.frame = newFrame;
[self.directionsView addSubview:label];
}
Instead of initialising your label with an y position of (i+1)*25, you should store your last label's bottom position
CGFloat lastLabelBottomCoordinate = 25;
CGFloat spaceBetweenLines = 10;
for (int i = 0; i < 10; i++)
{
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0, lastLabelBottomCoordinate + spaceBetweenLines,280,25)];
label.lineBreakMode = NSLineBreakByWordWrapping; //multiple lines in a label
label.numberOfLines = 0;
label.text =[NSString stringWithFormat: #"This is a very long text to see if the text have more than 2 lines"];
[label sizeToFit]; // resize the width and height to fit the text
NSLog(#"Actual height is: %f", label.frame.size.height); // Use this for spacing any further elements
CGSize expectedLabelSize = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName : label.font}
context:nil].size;
//adjust the label the the new height.
CGRect newFrame = label.frame;
newFrame.size.height = expectedLabelSize.height;
label.frame = newFrame;
lastLabelBottomCoordinate = label.frame.origin.y + label.frame.size.height;
[self.view addSubview:label];
}
This is how it looks:

Set UILabel font size according to its frame size on IOS8?

I found a lot of solution with the property “adjustsFontSizeToFitWidth" , but none of these solutions works on IOS8.
I develop a responsive app and the label font size has to change according to the screen width...
I have :
label = [[UILabel alloc] init];
label.numberOfLines = 1;
label.adjustsFontSizeToFitWidth = YES;
label.font = [UIFont fontWithName:FONT_DIGITAL size:60];
[label setMinimumScaleFactor:8.0/label.font.pointSize];
label.textAlignment = NSTextAlignmentCenter;
label.frame = CGRectMake(0, 0, self.width, self.height);
label.text = #"TEXT";
[self addSubview:valueLabel];
Someone has a solution?
You should set your label's auto shrink property as shown in below image.
Hope this helps.
Following answer is a hack (not the best solution), but it works, so if you want, you can try:
- (void) sizeLabel: (UILabel *) label toRect: (CGRect) labelRect {
// Set the frame of the label to the targeted rectangle
label.frame = labelRect;
// Try all font sizes from largest to smallest font size
CGFloat fontSize = 16.0f;
CGFloat minFontSize = 5.0f;
// Fit label width wize
CGSize constraintSize = CGSizeMake(label.frame.size.width, MAXFLOAT);
do {
// Set current font size
label.font = [UIFont fontWithName:label.font.fontName size:fontSize];
// Find label size for current font size
CGRect textRect = [[label text] boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:label.font}
context:nil];
CGSize labelSize = textRect.size;
// Done, if created label is within target size
if( labelSize.height <= label.frame.size.height )
break;
// Decrease the font size and try again
fontSize -= 1.0f;
} while (fontSize > minFontSize);
}

Dynamically changing font size of UILabel

I currently have a UILabel:
factLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 280, 100)];
factLabel.text = #"some text some text some text some text";
factLabel.backgroundColor = [UIColor clearColor];
factLabel.lineBreakMode = UILineBreakModeWordWrap;
factLabel.numberOfLines = 10;
[self.view addSubview:factLabel];
Throughout the life of my iOS application, factLabel gets a bunch of different values. Some with multiple sentences, others with just 5 or 6 words.
How can I set up the UILabel so that the font size changes so that the text always fits in the bounds I defined?
Single line:
factLabel.numberOfLines = 1;
factLabel.minimumFontSize = 8;
factLabel.adjustsFontSizeToFitWidth = YES;
The above code will adjust your text's font size down to (for example) 8 trying to fit your text within the label.
numberOfLines = 1 is mandatory.
Multiple lines:
For numberOfLines > 1 there is a method to figure out the size of final text through NSString's sizeWithFont:... UIKit addition methods, for example:
CGSize lLabelSize = [yourText sizeWithFont:factLabel.font
forWidth:factLabel.frame.size.width
lineBreakMode:factLabel.lineBreakMode];
After that you can just resize your label using resulting lLabelSize, for example (assuming that you will change only label's height):
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, factLabel.frame.size.width, lLabelSize.height);
iOS6
Single line:
Starting with iOS6, minimumFontSize has been deprecated. The line
factLabel.minimumFontSize = 8.;
can be changed to:
factLabel.minimumScaleFactor = 8./factLabel.font.pointSize;
iOS7
Multiple lines:
Starting with iOS7, sizeWithFont becomes deprecated.
Multiline case is reduced to:
factLabel.numberOfLines = 0;
factLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(factLabel.frame.size.width, CGFLOAT_MAX);
CGSize expectSize = [factLabel sizeThatFits:maximumLabelSize];
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, expectSize.width, expectSize.height);
iOS 13 (Swift 5):
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
minimumFontSize has been deprecated with iOS 6. You can use minimumScaleFactor.
yourLabel.adjustsFontSizeToFitWidth=YES;
yourLabel.minimumScaleFactor=0.5;
This will take care of your font size according width of label and text.
Single line- There are two ways, you can simply change.
1- Pragmatically (Swift 3)
Just add the following code
yourLabel.numberOfLines = 1;
yourLabel.minimumScaleFactor = 0.7;
yourLabel.adjustsFontSizeToFitWidth = true;
2 - Using UILabel Attributes inspector
i- Select your label- Set number of lines 1.
ii- Autoshrink- Select Minimum Font Scale from drop down
iii- Set Minimum Font Scale value as you wish , I have set 0.7 as in below image. (default is 0.5)
Based on #Eyal Ben Dov's answer you may want to create a category to make it flexible to use within another apps of yours.
Obs.: I've updated his code to make compatible with iOS 7
-Header file
#import <UIKit/UIKit.h>
#interface UILabel (DynamicFontSize)
-(void) adjustFontSizeToFillItsContents;
#end
-Implementation file
#import "UILabel+DynamicFontSize.h"
#implementation UILabel (DynamicFontSize)
#define CATEGORY_DYNAMIC_FONT_SIZE_MAXIMUM_VALUE 35
#define CATEGORY_DYNAMIC_FONT_SIZE_MINIMUM_VALUE 3
-(void) adjustFontSizeToFillItsContents
{
NSString* text = self.text;
for (int i = CATEGORY_DYNAMIC_FONT_SIZE_MAXIMUM_VALUE; i>CATEGORY_DYNAMIC_FONT_SIZE_MINIMUM_VALUE; i--) {
UIFont *font = [UIFont fontWithName:self.font.fontName size:(CGFloat)i];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:#{NSFontAttributeName: font}];
CGRect rectSize = [attributedText boundingRectWithSize:CGSizeMake(self.frame.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (rectSize.size.height <= self.frame.size.height) {
self.font = [UIFont fontWithName:self.font.fontName size:(CGFloat)i];
break;
}
}
}
#end
-Usage
#import "UILabel+DynamicFontSize.h"
[myUILabel adjustFontSizeToFillItsContents];
Cheers
It's 2015. I had to go to find a blog post that would explain how to do it for the latest version of iOS and XCode with Swift so that it would work with multiple lines.
set “Autoshrink” to “Minimum font size.”
set the font to the largest desirable font size (I chose 20)
Change “Line Breaks” from “Word Wrap” to “Truncate Tail.”
Source:
http://beckyhansmeyer.com/2015/04/09/autoshrinking-text-in-a-multiline-uilabel/
Swift version:
textLabel.adjustsFontSizeToFitWidth = true
textLabel.minimumScaleFactor = 0.5
Here's a Swift extension for UILabel. It runs a binary search algorithm to resize the font based off the width and height of the label's bounds. Tested to work with iOS 9 and autolayout.
USAGE: Where <label> is your pre-defined UILabel that needs font resizing
<label>.fitFontForSize()
By Default, this function searches in within the range of 5pt and 300pt font sizes and sets the font to fit its text "perfectly" within the bounds (accurate within 1.0pt). You could define the parameters so that it, for example, searches between 1pt and the label's current font size accurately within 0.1pts in the following way:
<label>.fitFontForSize(1.0, maxFontSize: <label>.font.pointSize, accuracy:0.1)
Copy/Paste the following code into your file
extension UILabel {
func fitFontForSize(var minFontSize : CGFloat = 5.0, var maxFontSize : CGFloat = 300.0, accuracy : CGFloat = 1.0) {
assert(maxFontSize > minFontSize)
layoutIfNeeded() // Can be removed at your own discretion
let constrainedSize = bounds.size
while maxFontSize - minFontSize > accuracy {
let midFontSize : CGFloat = ((minFontSize + maxFontSize) / 2)
font = font.fontWithSize(midFontSize)
sizeToFit()
let checkSize : CGSize = bounds.size
if checkSize.height < constrainedSize.height && checkSize.width < constrainedSize.width {
minFontSize = midFontSize
} else {
maxFontSize = midFontSize
}
}
font = font.fontWithSize(minFontSize)
sizeToFit()
layoutIfNeeded() // Can be removed at your own discretion
}
}
NOTE: Each of the layoutIfNeeded() calls can be removed at your own discretion
Its a little bit not sophisticated but this should work,
for example lets say you want to cap your uilabel to 120x120, with max font size of 28:
magicLabel.numberOfLines = 0;
magicLabel.lineBreakMode = NSLineBreakByWordWrapping;
...
magicLabel.text = text;
for (int i = 28; i>3; i--) {
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:(CGFloat)i] constrainedToSize:CGSizeMake(120.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
if (size.height < 120) {
magicLabel.font = [UIFont systemFontOfSize:(CGFloat)i];
break;
}
}
Just send the sizeToFit message to the UITextView. It will adjust its own height to just fit its text. It will not change its own width or origin.
[textViewA1 sizeToFit];
Swift 2.0 Version:
private func adapteSizeLabel(label: UILabel, sizeMax: CGFloat) {
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
let maximumLabelSize = CGSizeMake(label.frame.size.width, sizeMax);
let expectSize = label.sizeThatFits(maximumLabelSize)
label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, expectSize.width, expectSize.height)
}
This solution works for multiline:
After following several articles, and requiring a function that would automatically scale the text and adjust the line count to best fit within the given label size, I wrote a function myself. (ie. a short string would fit nicely on one line and use a large amount of the label frame, whereas a long strong would automatically split onto 2 or 3 lines and adjust the size accordingly)
Feel free to re-use it and tweak as required. Make sure you call it after viewDidLayoutSubviews has finished so that the initial label frame has been set.
+ (void)setFontForLabel:(UILabel *)label withMaximumFontSize:(float)maxFontSize andMaximumLines:(int)maxLines {
int numLines = 1;
float fontSize = maxFontSize;
CGSize textSize; // The size of the text
CGSize frameSize; // The size of the frame of the label
CGSize unrestrictedFrameSize; // The size the text would be if it were not restricted by the label height
CGRect originalLabelFrame = label.frame;
frameSize = label.frame.size;
textSize = [label.text sizeWithAttributes:#{NSFontAttributeName:[UIFont systemFontOfSize: fontSize]}];
// Work out the number of lines that will need to fit the text in snug
while (((textSize.width / numLines) / (textSize.height * numLines) > frameSize.width / frameSize.height) && (numLines < maxLines)) {
numLines++;
}
label.numberOfLines = numLines;
// Get the current text size
label.font = [UIFont systemFontOfSize:fontSize];
textSize = [label.text boundingRectWithSize:CGSizeMake(frameSize.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName : label.font}
context:nil].size;
// Adjust the frame size so that it can fit text on more lines
// so that we do not end up with truncated text
label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, label.frame.size.width);
// Get the size of the text as it would fit into the extended label size
unrestrictedFrameSize = [label textRectForBounds:CGRectMake(0, 0, label.bounds.size.width, CGFLOAT_MAX) limitedToNumberOfLines:numLines].size;
// Keep reducing the font size until it fits
while (textSize.width > unrestrictedFrameSize.width || textSize.height > frameSize.height) {
fontSize--;
label.font = [UIFont systemFontOfSize:fontSize];
textSize = [label.text boundingRectWithSize:CGSizeMake(frameSize.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName : label.font}
context:nil].size;
unrestrictedFrameSize = [label textRectForBounds:CGRectMake(0, 0, label.bounds.size.width, CGFLOAT_MAX) limitedToNumberOfLines:numLines].size;
}
// Set the label frame size back to original
label.frame = originalLabelFrame;
}
Here is the fill code of a UILabel subclass that implements animated font size change:
#interface SNTextLayer : CATextLayer
#end
#implementation SNTextLayer
- (void)drawInContext:(CGContextRef)ctx {
// We override this to make text appear at the same vertical positon as in UILabel
// (otherwise it's shifted tdown)
CGFloat height = self.bounds.size.height;
float fontSize = self.fontSize;
// May need to adjust this somewhat if it's not aligned perfectly in your implementation
float yDiff = (height-fontSize)/2 - fontSize/10;
CGContextSaveGState(ctx);
CGContextTranslateCTM(ctx, 0.0, yDiff);
[super drawInContext:ctx];
CGContextRestoreGState(ctx);
}
#end
#interface SNAnimatableLabel ()
#property CATextLayer* textLayer;
#end
#interface SNAnimatableLabel : UILabel
- (void)animateFontToSize:(CGFloat)fontSize withDuration:(double)duration;
#end
#implementation SNAnimatableLabel
- (void)awakeFromNib {
[super awakeFromNib];
_textLayer = [SNTextLayer new];
_textLayer.backgroundColor = self.backgroundColor.CGColor;
_textLayer.foregroundColor = self.textColor.CGColor;
_textLayer.font = CGFontCreateWithFontName((CFStringRef)self.font.fontName);
_textLayer.frame = self.bounds;
_textLayer.string = self.text;
_textLayer.fontSize = self.font.pointSize;
_textLayer.contentsScale = [UIScreen mainScreen].scale;
[_textLayer setPosition: CGPointMake(CGRectGetMidX(_textLayer.frame), CGRectGetMidY(_textLayer.frame))];
[_textLayer setAnchorPoint: CGPointMake(0.5, 0.5)];
[_textLayer setAlignmentMode: kCAAlignmentCenter];
self.textColor = self.backgroundColor;
// Blend text with background, so that it doens't interfere with textlayer text
[self.layer addSublayer:_textLayer];
self.layer.masksToBounds = NO;
}
- (void)setText:(NSString *)text {
_textLayer.string = text;
super.text = text;
}
- (void)layoutSubviews {
[super layoutSubviews];
// Need to enlarge the frame, otherwise the text may get clipped for bigger font sizes
_textLayer.frame = CGRectInset(self.bounds, -5, -5);
}
- (void)animateFontToSize:(CGFloat)fontSize withDuration:(double)duration {
[CATransaction begin];
[CATransaction setAnimationDuration:duration];
_textLayer.fontSize = fontSize;
[CATransaction commit];
}

Resources