This question has asked many times, however I have not clear, got wrong output. So please anyone help..
CGSize maximumSize = CGSizeMake(208, 21);
UIFont *myFont = [UIFont fontWithName:#"Helvetica" size:14];
CGSize myStringSize = [my_string sizeWithFont:myFont
constrainedToSize:maximumSize
lineBreakMode:self.my_label.lineBreakMode];
my_label.numberOfLines = 0;
my_label.frame.size = myStringSize;
I have a label of size (208, 21), I have used the following code to get actual height required for NSString with respect to my label width, I want fixed width, only height need to vary so I can set in label. But it always give lower height than actual.. Am I doing anything wrong here..
thanks..
In your example use a maximum size with a (very) large height instead of restricting the height:
CGSize maximumSize = CGSizeMake(208, CGFLOAT_MAX);
This way there will always be enough height to expand to, while limiting the width to the width you actually want.
Try this :
-(CGSize) calculateWidthOfString:(NSString*)textString withFont:(UIFont*)font
{
CGSize maximumSize = CGSizeMake(9999, 22);
CGSize size = [textString sizeWithFont:font
constrainedToSize:maximumSize
lineBreakMode:UILineBreakModeWordWrap];
return size;
}
call this function with stringObject and Font Name, Size
it returns width of string with constant height "22" change this value as u want.
hope this will helps u.
+ (CGSize) calculateLabelHeightWith:(CGFloat)width text:(NSString*)textString
{
CGSize maximumSize = CGSizeMake(width, 9999);
CGSize size = [textString sizeWithFont:[UIFont fontWithName:#"Helvetica" size:24]
constrainedToSize:maximumSize
lineBreakMode:UILineBreakModeWordWrap];
return size;
}
+ (CGSize) calculateLabelWidthOfString:(NSString*)textString withFont:(UIFont*)font
{
CGSize maximumSize = CGSizeMake(9999, 22);
CGSize size = [textString sizeWithFont:font
constrainedToSize:maximumSize
lineBreakMode:UILineBreakModeWordWrap];
return size;
}
use these two for height or width
How can I adjust the label Width according to the text? If text length is small I want the label width small...If text length is small I want the label width according to that text length. Is it possible?
Actually I have Two UIlabels. I need to place these two nearby. But if the first label's text is too small there will be a big gap. I want to remove this gap.
//use this for custom font
CGFloat width = [label.text sizeWithFont:[UIFont fontWithName:#"ChaparralPro-Bold" size:40 ]].width;
//use this for system font
CGFloat width = [label.text sizeWithFont:[UIFont systemFontOfSize:40 ]].width;
label.frame = CGRectMake(point.x, point.y, width,height);
//point.x, point.y -> origin for label;
//height -> your label height;
Function sizeWithFont: is deprecated in iOS 7.0, so you have to use sizeWithAttributes: for iOS 7.0+. Also to suport older versions, this code below can be used:
CGFloat width;
if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0)
{
width = [text sizeWithFont:[UIFont fontWithName:#"Helvetica" size:16.0 ]].width;
}
else
{
width = ceil([text sizeWithAttributes:#{NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:16.0]}].width);
}
Using function ceil() on result of sizeWithAttributes: is recommended by Apple documentation:
"This method returns fractional sizes; to use a returned size to size views, you must raise its value to the nearest higher integer using the ceil function."
sizeWithAttributes
// In swift 2.0
let lblDescription = UILabel(frame: CGRectMake(0, 0, 200, 20))
lblDescription.numberOfLines = 0
lblDescription.text = "Sample text to show its whatever may be"
lblDescription.sizeToFit()
// Its automatically Adjust the height
Try these options,
UIFont *myFont = [UIFont boldSystemFontOfSize:15.0];
// Get the width of a string ...
CGSize size = [#"Some string here" sizeWithFont:myFont];
// Get the width of a string when wrapping within a particular width
NSString *mystring = #"some strings some string some strings...";
CGSize size = [mystring sizeWithFont:myFont
forWidth:150.0
lineBreakMode:UILineBreakModeWordWrap];
You can also try with [label sizeToFit]; Using this method, you can set frame of two labels as,
[firstLabel sizeToFit];
[secondLabel sizeToFit];
secondLabel.frame = CGRectMake(CGRectGetMaxX(firstLabel.frame), secondLabel.origin.y, secondLabel.frame.size.width, secondLabel.frame.size.height);
sizeWithFont constrainedToSize:lineBreakMode: is the original method to use. Here is an example of how to use it is below:
//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;
just use to if you using constrain in your view or xib or cell
[LBl sizeToFit];
if its not working then
dispatch_async(dispatch_get_main_queue(), ^{
[LBl sizeToFit];
});
Try the following:
/* Consider these two labels as the labels that you use,
and that these labels have been initialized */
UILabel* firstLabel;
UILabel* secondLabel;
CGSize labelSize = [firstLabel.text sizeWithFont:[UIFont systemFontOfSize:12]];
//change the font size, or font as per your requirements
CGRect firstLabelRect = firstLabel.frame;
firstLabelRect.size.width = labelSize.width;
//You will get the width as per the text in label
firstLabel.frame = firstLabelRect;
/* Now, let's change the frame for the second label */
CGRect secondLabelRect;
CGFloat x = firstLabelRect.origin.x;
CGFloat y = firstLabelRect.origin.y;
x = x + labelSize.width + 20; //There are some changes here.
secondLabelRect = secondLabel.frame;
secondLabelRect.origin.x = x;
secondLabelRect.origin.y = y;
secondLabel.frame = secondLabelRect;
Why doesn't this work? It always returns 18 no matter the length of the string. There is this thread, but not a definitive answer.
NSString * t = #"<insert super super long string here>";
CGSize size = [t sizeWithFont:[UIFont systemFontOfSize:14.0] forWidth:285 lineBreakMode:UILineBreakModeWordWrap];
NSLog(#"size.height is %f and text is %#", size.height, t);
Thanks,
Todd
Use sizeWithFont:constrainedToSize:lineBreakMode: instead.
NSString * t = #"<insert super super long string here>";
CGSize constrainSize = CGSizeMake(285, MAXFLOAT);
CGSize size = [t sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:constrainSize lineBreakMode:UILineBreakModeWordWrap];
NSLog(#"size.height is %f and text is %#", size.height, t);
DEPRECATED Method: NS_DEPRECATED_IOS(2_0, 7_0)
- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:");
Example
CGSize titleTextSize = [self.titleLabel.text sizeWithFont:self.myLabel.font forWidth:myLabelWidth lineBreakMode:NSLineBreakByTruncatingTail];
New Approach
Use :
- (CGRect)boundingRectWithSize:(CGSize)size
options:(NSStringDrawingOptions)options
attributes:(NSDictionary<NSString *,
id> *)attributes
context:(NSStringDrawingContext *)context
Example:
// Create a paragraph style with the desired line break mode
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
// Create the attributes dictionary with the font and paragraph style
NSDictionary *attributes = #{
NSFontAttributeName:self.myLabel.font,
NSParagraphStyleAttributeName:paragraphStyle
};
// Call boundingRectWithSize:options:attributes:context for the string
CGRect textRect = [self.countLabel.text boundingRectWithSize:CGSizeMake(widthOfMyLabel, 999999.0f)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
See Appple Doc
CGSize size = [t sizeWithFont:[UIFont fontWithName:#"Arial-BoldMT" size:16.0] constrainedToSize:CGSizeMake(220,500) lineBreakMode:UILineBreakModeWordWrap];
I want to change the uilabel height as per content and display it in a uitableview cell, there is a custom cell and cell is expand as per uilabel height
When button is pressed then and then cell height is expand as per the uilabel height
Thank you in Advance :-)
//Calculate the size based on the font and linebreak mode of your label
CGSize maxLabelSize = CGSizeMake(300,9999);
CGSize expectedLabelSize = [myString sizeWithFont:myLabel.font
constrainedToSize:maxLabelSize
lineBreakMode:myLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = myLabel.frame;
newFrame.size.height = expectedLabelSize.height;
myLabel.frame = newFrame;
Try this
[label sizeToFit];
Note that label will increase it's height keeping it's width the same.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = displayText;
//CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize constraint = CGSizeMake(tableView.frame.size.width - 30, 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
return height + 30;
}
Calculate the size of the label text & than set coordinates as
CGSize labelWidth=[_label.text sizeWithFont:[UIFont fontWithName:#"Verdana" size:12] constrainedToSize:CGSizeMake(200, 15) lineBreakMode:UILineBreakModeTailTruncation];
Yeah, there's this cool myLabel.adjustsFontSizeToFitWidth = YES; property. But as soon as the label has two lines or more, it won't resize the text to anything. So it just gets truncated with ... if it doesn't fit into the rect.
Is there another way to do it?
If you want to make sure the label fits in the rectangle both width and height wise you can try different font size on the label to see if one will fit.
This snippet starts at 300 pt and tries to fit the label in the targeted rectangle by reducing the font size.
- (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
int fontSize = 300;
int minFontSize = 5;
// 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 -= 2;
} while (fontSize > minFontSize);
}
I think the above explains what goes on. A faster implementation could use caching and argarcians binary search as follows
+ (CGFloat) fontSizeForString: (NSString*) s inRect: (CGRect) labelRect {
// Cache repeat queries
static NSMutableDictionary* mutableDict = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
mutableDict = [NSMutableDictionary dictionary];
});
NSString* key = [NSString stringWithFormat:#"%#_%d_%d", s, (int) labelRect.size.width, (int) labelRect.size.height];
NSNumber* value = [mutableDict objectForKey:key];
if (value)
return value.doubleValue;
// Set the frame of the label to the targeted rectangle
UILabel* label = [[UILabel alloc] init];
label.text = s;
label.frame = labelRect;
// Hopefully between 5 and 300
CGFloat theSize = (CGFloat) [self binarySearchForFontSizeForLabel:label withMinFontSize:5 withMaxFontSize:300 withSize:label.frame.size];
[mutableDict setObject:#(theSize) forKey:key];
return theSize;
}
+ (NSInteger)binarySearchForFontSizeForLabel:(UILabel *)label withMinFontSize:(NSInteger)minFontSize withMaxFontSize:(NSInteger)maxFontSize withSize:(CGSize)size {
// If the sizes are incorrect, return 0, or error, or an assertion.
if (maxFontSize < minFontSize) {
return maxFontSize;
}
// Find the middle
NSInteger fontSize = (minFontSize + maxFontSize) / 2;
// Create the font
UIFont *font = [UIFont fontWithName:label.font.fontName size:fontSize];
// Create a constraint size with max height
CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT);
// Find label size for current font size
CGRect rect = [label.text boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName : font}
context:nil];
CGSize labelSize = rect.size;
// EDIT: The next block is modified from the original answer posted in SO to consider the width in the decision. This works much better for certain labels that are too thin and were giving bad results.
if (labelSize.height >= (size.height + 10) && labelSize.width >= (size.width + 10) && labelSize.height <= (size.height) && labelSize.width <= (size.width)) {
return fontSize;
} else if (labelSize.height > size.height || labelSize.width > size.width) {
return [self binarySearchForFontSizeForLabel:label withMinFontSize:minFontSize withMaxFontSize:fontSize - 1 withSize:size];
} else {
return [self binarySearchForFontSizeForLabel:label withMinFontSize:fontSize + 1 withMaxFontSize:maxFontSize withSize:size];
}
}
I found Niels' answer to be the best answer for this issue. However, I have a UIView that can have 100 labels where I need to fit the text, so this process was very inefficient and I could feel the hit in performance.
Here is his code modified to use a binary search instead, rather than a linear search. Now it works very efficiently.
- (NSInteger)binarySearchForFontSizeForLabel:(UILabel *)label withMinFontSize:(NSInteger)minFontSize withMaxFontSize:(NSInteger)maxFontSize withSize:(CGSize)size {
// If the sizes are incorrect, return 0, or error, or an assertion.
if (maxFontSize < minFontSize) {
return 0;
}
// Find the middle
NSInteger fontSize = (minFontSize + maxFontSize) / 2;
// Create the font
UIFont *font = [UIFont fontWithName:label.font.fontName size:fontSize];
// Create a constraint size with max height
CGSize constraintSize = CGSizeMake(size.width, MAXFLOAT);
// Find label size for current font size
CGRect rect = [label.text boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName : font}
context:nil];
CGSize labelSize = rect.size;
// EDIT: The next block is modified from the original answer posted in SO to consider the width in the decision. This works much better for certain labels that are too thin and were giving bad results.
if (labelSize.height >= (size.height + 10) && labelSize.width >= (size.width + 10) && labelSize.height <= (size.height) && labelSize.width <= (size.width)) {
return fontSize;
} else if (labelSize.height > size.height || labelSize.width > size.width) {
return [self binarySearchForFontSizeForLabel:label withMinFontSize:minFontSize withMaxFontSize:fontSize - 1 withSize:size];
} else {
return [self binarySearchForFontSizeForLabel:label withMinFontSize:fontSize + 1 withMaxFontSize:maxFontSize withSize:size];
}
}
- (void)sizeBinaryLabel:(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
int maxFontSize = 300;
int minFontSize = 5;
NSInteger size = [self binarySearchForFontSizeForLabel:label withMinFontSize:minFontSize withMaxFontSize:maxFontSize withSize:label.frame.size];
label.font = [UIFont fontWithName:label.font.fontName size:size];
}
Credit goes also to https://gist.github.com/988219
Here's Swift version according to #NielsCastle answer, using binary search
extension UILabel{
func adjustFontSizeToFitRect(rect : CGRect){
if text == nil{
return
}
frame = rect
let maxFontSize: CGFloat = 100.0
let minFontSize: CGFloat = 5.0
var q = Int(maxFontSize)
var p = Int(minFontSize)
let constraintSize = CGSize(width: rect.width, height: CGFloat.max)
while(p <= q){
let currentSize = (p + q) / 2
font = font.fontWithSize( CGFloat(currentSize) )
let text = NSAttributedString(string: self.text!, attributes: [NSFontAttributeName:font])
let textRect = text.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, context: nil)
let labelSize = textRect.size
if labelSize.height < frame.height && labelSize.height >= frame.height-10 && labelSize.width < frame.width && labelSize.width >= frame.width-10 {
break
}else if labelSize.height > frame.height || labelSize.width > frame.width{
q = currentSize - 1
}else{
p = currentSize + 1
}
}
}
}
Usage
label.adjustFontSizeToFitRect(rect)
often just
label.adjustFontSizeToFitRect(rect.frame)
This solution (based on this answer) works with auto-layout and performs a binary search to find the best font size.
The only caveat I have found is that you can't specify the number of lines (because AFAIK you can't tell boundingRectWithSize how many lines you want).
AdjustableLabel.h
#import <UIKit/UIKit.h>
#interface AdjustableLabel : UILabel
/**
If set to YES, font size will be automatically adjusted to frame.
Note: numberOfLines can't be specified so it will be set to 0.
*/
#property(nonatomic) BOOL adjustsFontSizeToFitFrame;
#end
AdjustableLabel.m
#import "AdjustableLabel.h"
#interface AdjustableLabel ()
#property(nonatomic) BOOL fontSizeAdjusted;
#end
// The size found S satisfies: S fits in the frame and and S+DELTA doesn't.
#define DELTA 0.5
#implementation AdjustableLabel
- (void)setAdjustsFontSizeToFitFrame:(BOOL)adjustsFontSizeToFitFrame
{
_adjustsFontSizeToFitFrame = adjustsFontSizeToFitFrame;
if (adjustsFontSizeToFitFrame) {
self.numberOfLines = 0; // because boundingRectWithSize works like this was 0 anyway
}
}
- (void)layoutSubviews
{
[super layoutSubviews];
if (self.adjustsFontSizeToFitFrame && !self.fontSizeAdjusted)
{
self.fontSizeAdjusted = YES; // to avoid recursion, because adjustFontSizeToFrame will trigger this method again
[self adjustFontSizeToFrame];
}
}
- (void) adjustFontSizeToFrame
{
UILabel* label = self;
if (label.text.length == 0) return;
// Necessary or single-char texts won't be correctly adjusted
BOOL checkWidth = label.text.length == 1;
CGSize labelSize = label.frame.size;
// Fit label width-wise
CGSize constraintSize = CGSizeMake(checkWidth ? MAXFLOAT : labelSize.width, MAXFLOAT);
// Try all font sizes from largest to smallest font size
CGFloat maxFontSize = 300;
CGFloat minFontSize = 5;
NSString* text = label.text;
UIFont* font = label.font;
while (true)
{
// Binary search between min and max
CGFloat fontSize = (maxFontSize + minFontSize) / 2;
// Exit if approached minFontSize enough
if (fontSize - minFontSize < DELTA/2) {
font = [UIFont fontWithName:font.fontName size:minFontSize];
break; // Exit because we reached the biggest font size that fits
} else {
font = [UIFont fontWithName:font.fontName size:fontSize];
}
// Find label size for current font size
CGRect rect = [text boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName : font}
context:nil];
// Now we discard a half
if( rect.size.height <= labelSize.height && (!checkWidth || rect.size.width <= labelSize.width) ) {
minFontSize = fontSize; // the best size is in the bigger half
} else {
maxFontSize = fontSize; // the best size is in the smaller half
}
}
label.font = font;
}
#end
Usage
AdjustableLabel* label = [[AdjustableLabel alloc] init];
label.adjustsFontSizeToFitFrame = YES;
// In case you change the font, the size you set doesn't matter
label.font = [UIFont fontWithName:#"OpenSans-Light" size:20];
Here's a Swift extension for UILabel. It runs a binary search algorithm to resize the font and bounds of the label, and is tested to work for iOS 12.
USAGE: Resizes the font to fit a size of 100x100 (accurate within 1.0 font point) and aligns it to top.
let adjustedSize = <label>.fitFontForSize(CGSizeMake(100, 100))
<label>.frame = CGRect(x: 0, y: 0, width: 100, height: adjustedSize.height)
Copy/Paste the following into your file:
extension UILabel {
#discardableResult func fitFontForSize(_ constrainedSize: CGSize,
maxFontSize: CGFloat = 100,
minFontSize: CGFloat = 5,
accuracy: CGFloat = 1) -> CGSize {
assert(maxFontSize > minFontSize)
var minFontSize = minFontSize
var maxFontSize = maxFontSize
var fittingSize = constrainedSize
while maxFontSize - minFontSize > accuracy {
let midFontSize: CGFloat = ((minFontSize + maxFontSize) / 2)
font = font.withSize(midFontSize)
fittingSize = sizeThatFits(constrainedSize)
if fittingSize.height <= constrainedSize.height
&& fittingSize.width <= constrainedSize.width {
minFontSize = midFontSize
} else {
maxFontSize = midFontSize
}
}
return fittingSize
}
}
This function will not change the label size, only the font property is affected. You can use the returned size value to adjust the layout of the label.
If someone is looking for a MonoTouch/Xamarin.iOS implementation, as I did ... here you go:
private int BinarySearchForFontSizeForText(NSString text, int minFontSize, int maxFontSize, SizeF size)
{
if (maxFontSize < minFontSize)
return minFontSize;
int fontSize = (minFontSize + maxFontSize) / 2;
UIFont font = UIFont.BoldSystemFontOfSize(fontSize);
var constraintSize = new SizeF(size.Width, float.MaxValue);
SizeF labelSize = text.StringSize(font, constraintSize, UILineBreakMode.WordWrap);
if (labelSize.Height >= size.Height + 10 && labelSize.Width >= size.Width + 10 && labelSize.Height <= size.Height && labelSize.Width <= size.Width)
return fontSize;
else if (labelSize.Height > size.Height || labelSize.Width > size.Width)
return BinarySearchForFontSizeForText(text, minFontSize, fontSize - 1, size);
else
return BinarySearchForFontSizeForText(text, fontSize + 1, maxFontSize, size);
}
private void SizeLabelToRect(UILabel label, RectangleF labelRect)
{
label.Frame = labelRect;
int maxFontSize = 300;
int minFontSize = 5;
int size = BinarySearchForFontSizeForText(new NSString(label.Text), minFontSize, maxFontSize, label.Frame.Size);
label.Font = UIFont.SystemFontOfSize(size);
}
It's a translation of agarcian's code from Objective-C to C#, with a small modification: as the returning result has always been 0 (see the comment of borked) I am returning the calculated minFontSize, which results in a correct font size.
Also set myLabel.numberOfLines = 10 or to whatever the max number of lines you want.
All these are interesting solutions to the original problem, however all of them are also missing an important thing: If you solely rely on the familyName to get the next font to test, you're losing the weight information and possibly more advanced attributes like small caps, figure style, etc.
A better approach is instead of passing the font name around and doing [UIFont fontWithName:someFontName size:someFontSize], passing UIFontDescriptor objects along and then doing
[UIFont fontWithDescriptor:someFontDescriptor size:someFontSize].
Since I didn't find a working solution answering to all my needs using the above answers, I have created my own components providing the following features: FittableFontLabel
Adjust font to fit height and width when using multilines label
Adjust font to fit width when using single line label, the height label will resize itself
Support for NSAttributedStrings as well as basic string
Auto adjusting the size when changing a label text / frame
...
If any of you is interesting, it's a full swift library available using
CocoaPods: https://github.com/tbaranes/FittableFontLabel
Niels Castle code work find.
Here is the same idea with a different implementation.
My solution is more precise but also much more CPU intensive.
Add this function to a class who inherit UILabel.
-(void)fitCurrentFrame{
CGSize iHave = self.frame.size;
BOOL isContained = NO;
do{
CGSize iWant = [self.text sizeWithFont:self.font];
if(iWant.width > iHave.width || iWant.height > iHave.height){
self.font = [UIFont fontWithName:self.font.fontName size:self.font.pointSize - 0.1];
isContained = NO;
}else{
isContained = YES;
}
}while (isContained == NO);
}
I have created Category for UILabel based on #agarcian's answer. But i calculate fontSize depending on square needed on screen for drawing text. This method not need loops and calculating is done by one iteration.
Here the .h file:
// UILabel+Extended.h
// Created by Firuz on 16/08/14.
// Copyright (c) 2014. All rights reserved.
#import <UIKit/UIKit.h>
#interface UILabel (Extended)
/** This method calculate the optimal font size for current number of lines in UILable. Mus be called after drawing UILabel view */
- (NSInteger)fontSizeWithMinFontSize:(NSInteger)minFontSize withMaxFontSize:(NSInteger)maxFontSize;
#end
And here the .m file:
// UILabel+Extended.m
// Created by Firuz on 16/08/14.
// Copyright (c) 2014. All rights reserved.
#import "UILabel+Extended.h"
#implementation UILabel (Extended)
- (NSInteger)fontSizeWithMinFontSize:(NSInteger)minFontSize withMaxFontSize:(NSInteger)maxFontSize
{
if (maxFontSize < minFontSize) {
return 0;
}
UIFont *font = [UIFont fontWithName:self.font.fontName size:maxFontSize];
CGFloat lineHeight = [font lineHeight];
CGSize constraintSize = CGSizeMake(MAXFLOAT, lineHeight);
CGRect rect = [self.text boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName : font}
context:nil];
CGFloat labelSqr = self.frame.size.width * self.frame.size.height;
CGFloat stringSqr = rect.size.width/self.frame.size.width * (lineHeight + font.pointSize) * self.frame.size.width;
CGFloat multiplyer = labelSqr/stringSqr;
if (multiplyer < 1) {
if (minFontSize < maxFontSize*multiplyer) {
return maxFontSize * multiplyer;
} else {
return minFontSize;
}
}
return maxFontSize;
}
#end
All binary searches are good, but stop recursion using frame checks not so logically. More nicely check font size, cause UIFont supports float size and this font is more suitable.
Plus using label paragraph style to calculate size morу exactly.
If someone interesting, you can look bellow code:
static UIFont * ___suitableFontInRangePrivate(const CGSize labelSize,
NSParagraphStyle * paragraphStyle,
NSString * fontName,
NSString * text,
const CGFloat minSize,
const CGFloat maxSize)
{
// Font size in range, middle size between max & min.
const CGFloat currentSize = minSize + ((maxSize - minSize) / 2);
// Font with middle size.
UIFont * currentFont = [UIFont fontWithName:fontName size:currentSize];
// Calculate text height.
const CGFloat textHeight = [text boundingRectWithSize:CGSizeMake(labelSize.width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{ NSFontAttributeName : currentFont, NSParagraphStyleAttributeName : paragraphStyle }
context:nil].size.height;
CGFloat min, max;
if (textHeight > labelSize.height)
{
// Take left range part.
min = minSize;
max = currentSize;
}
else
{
// Take right range part.
min = currentSize;
max = maxSize;
}
// If font size in int range [0.0; 2.0] - got it, othervice continue search.
return ((max - min) <= 2.0) ? currentFont : ___suitableFontInRangePrivate(labelSize, paragraphStyle, fontName, text, min, max);
}
void UILabelAdjustsFontSizeToFrame(UILabel * label)
{
if (!label) return;
NSString * text = [label text];
__block NSParagraphStyle * style = nil;
[[label attributedText] enumerateAttributesInRange:NSMakeRange(0, [text length])
options:(NSAttributedStringEnumerationOptions)0
usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop){
id paragraphStyle = [attrs objectForKey:#"NSParagraphStyle"];
if (paragraphStyle) style = [paragraphStyle retain];
}];
if (!style)
{
NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
if (!paragraphStyle) paragraphStyle = [[NSMutableParagraphStyle alloc] init];
if (paragraphStyle)
{
[paragraphStyle setLineBreakMode:[label lineBreakMode]];
[paragraphStyle setAlignment:[label textAlignment]];
}
style = paragraphStyle;
}
UIFont * suitableFont = ___suitableFontInRangePrivate([label frame].size, style, [[label font] fontName], text, 0, 500);
[label setFont:suitableFont];
[style release];
}
Swift 3 "binary search solution" based on this answer with minor improvements. Sample is in context of UITextView subclass:
func binarySearchOptimalFontSize(min: Int, max: Int) -> Int {
let middleSize = (min + max) / 2
if min > max {
return middleSize
}
let middleFont = UIFont(name: font!.fontName, size: CGFloat(middleSize))!
let attributes = [NSFontAttributeName : middleFont]
let attributedString = NSAttributedString(string: text, attributes: attributes)
let size = CGSize(width: bounds.width, height: .greatestFiniteMagnitude)
let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
let textSize = attributedString.boundingRect(with: size, options: options, context: nil)
if textSize.size.equalTo(bounds.size) {
return middleSize
} else if (textSize.height > bounds.size.height || textSize.width > bounds.size.width) {
return binarySearchOptimalFontSize(min: min, max: middleSize - 1)
} else {
return binarySearchOptimalFontSize(min: middleSize + 1, max: max)
}
}
I hope that helps someone.
#agarcian's answer was close but it didn't quite work for me, as someone else mentioned in a comment, it always returned 0.
Here is my attempt.
Cheers!
/**
* Returns the font size required in order to fit the specified text in the specified area.
* NB! When drawing, be sure to pass in the same options that we pass to boundingRectWithSize:options:attributes:context:
* Heavily modified form of: http://stackoverflow.com/a/14662750/1027452
*/
+(NSInteger)fontSizeForText:(NSString *)text withFont:(UIFont *)font inArea:(CGSize)areaSize minFontSize:(NSInteger)minFontSize maxFontSize:(NSInteger)maxFontSize
{
// If the sizes are incorrect, return 0, or error, or an assertion.
if (maxFontSize < minFontSize) {
return 0;
}
// Find the middle
NSInteger fontSize = (minFontSize + maxFontSize) / 2;
// Create the font
UIFont *f = [UIFont fontWithName:font.fontName size:fontSize];
// Create a constraint size with max height
CGSize constraintSize = CGSizeMake(areaSize.width, MAXFLOAT);
// Find label size for current font size
CGRect rect = [text boundingRectWithSize:constraintSize
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName : f}
context:nil];
CGSize labelSize = rect.size;
if (labelSize.height <= areaSize.height && labelSize.width <= areaSize.width )
{
return fontSize;
}
else if (labelSize.height > areaSize.height || labelSize.width > areaSize.width)
{
return [self fontSizeForText:text withFont:f inArea:areaSize minFontSize:minFontSize maxFontSize:maxFontSize -1];;
}
else
{
return [self fontSizeForText:text withFont:f inArea:areaSize minFontSize:minFontSize+1 maxFontSize:maxFontSize];;
}
}