determining UIFont's pointSize for a specific CGSize - ios

I have a specific CGSize of a UILabel, where I cannot expand the frame of UILabel and since it is a multi-line UILabels adjustsFontSizeToFitWidth method does not work.
So I figured I should create such function which looked like;
- (CGFloat)fontSizeWithText:(NSString*)text andFont:(UIFont*)font constrainedSize:(CGSize)size LBM:(UILineBreakMode)LBM
{
// check if text fits to label
CGSize labelSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(size.width, 9999) lineBreakMode:LBM];
// if not, decrease font size until it fits to the given size
while (labelSize.height > size.height) {
font = [UIFont fontWithName:font.fontName size:font.pointSize - 0.5];
labelSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(size.width, 9999) lineBreakMode:LBM];
}
return font.pointSize;
}
Usage:
// fit detail label by arranging font's size
CGFloat fontSize = [self fontSizeWithText:self.titleLabel.text andFont:self.titleLabel.font constrainedSize:self.titleLabel.frame.size LBM:self.titleLabel.lineBreakMode];
self.titleLabel.font = [UIFont fontWithName:self.titleLabel.font.fontName size:fontSize];
But with this method, I see that some of my texts doesn't fit to the UILabel s frame and gets truncated. There must be something I am missing. Any help for the code or any other suggestions on resolving "fitting a text with given font to a specific multi-line UILabel" would be great.

First lets quickly take a look at the problem as a whole. You're trying to fit text into a predefined frame and adjust the font size. This generally will not work terribly well, as you will quickly hit sizes FAR too small to read, even on a retina display. You should adjust the frame of your label to accommodate the excess text (where possible. Sometimes, truncation is the only option.)
Now that, that is out of the way, lets take a look at adjusting the font size. Despite not recommending it, I will still explain how best to go about it.
Important, this code is untested, and will more than likely require some tweaks, but that can be an exercise of the reader.
So the first thing we need to know is the height of a single line. Now, we have the height of the label, and the number of lines it can display, so we can determine this by simply dividing the label height by the number of lines.
CGFloat optimalLineHeight = CGRectGetHeight(label.frame) / label.numberOfLines;
You may have noticed that this may return lines taller than are actually needed. You will be able to implement additional checks and constraints to deal with this. At current though, the font size will also be able to grow, and not just shrink.
Now, getting the optimal line height is just part of the story. We now need to optimise the font size. Here's some code:
CGFloat optimumFontSize = 0.0;
BOOL optimumFontSizeFound = NO;
do {
CGSize charSize = [#"M" sizeWithFont:[UIFont systemFontOfSize:optimumFontSize]
constrainedToSize:CGSizeMake(100, 9999)
lineBreakMode:0];
if ( CGSizeGetHeight(charSize) > optimalLineHeight ) {
optimumFontSizeFound = YES;
}
else {
optimumFontSize++;
}
} while ( !optimumFontSizeFound );
So what does this do? In this we keep track of the optimumFontSize so far. We start with the assumption of a font size of 0, and we see how tall a single character using that font size is. If that height is greater than the optimal line height previously calculated, then the previous height is the optimal one. If not, we increase the size and repeat until we do find the optimal one.
There are still a lot of issues to overcome in this to make it work perfectly in all situations. This should ensure that you don't get visible vertical clipping of characters, but it can't ensure that all the text content will display in the frame. To do that you'll need to be more intelligent in how you determine the number of lines required, but again I'll leave that as an exercise of the reader.
Hope this helps you towards your goal.

Related

How to adjust UILabel font size to fit the fixed Rectangle (for iOS7 +)?

I know this question has been asked so many times and I have seen most of the solutions like
How to adjust font size of label to fit the rectangle?
How to calculate actual font point size in iOS 7 (not the bounding rectangle)?
NSString sizeWithFont: alternative in iOS7
What I want is that I want to adjust the font size in a given rect with WORD WRAPPING technique. The posts I mentioned above somehow adjust the font size but none of them is using word wrapping technique. Let say, I have a label
UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 60, 25)]; \\60px width
tempLabel.text = #"Internationalisation";
tempLabel.numberOfLines = 2;
Now it should wrap the text in one line (within 60 px) with minimum possible font. But it keeps the text in 2 lines with a bit bigger font and the text breaks up like "Internationali" in first line and "sation" in second. How can we apply word wrapping in it.
tempLabel.adjustsFontSizeToFitWidth = YES;
does not seem to work for two or more lines and
CGSize size = [self sizeWithFont:font
minFontSize:minFontSize
actualFontSize:&actualFontSize
forWidth:maxWidth
lineBreakMode:self.lineBreakMode];
is deprecated in iOS7+
So how can I resolve my Issue. Please do help. This is so important for me.

Positioning a UILabel directly beneath another UILabel

I have an addition to NSString which automatically resizes a UILabel depending on the text that's being read into it (I have a simple app showing quotations, so some are a few words, some a couple sentences). Below that quote label, I also have an author label, which (oddly enough) has the author of the quote in it.
I'm trying to position that author label directly beneath the quote label (as in, its y coordinate would be the quote label's y coordinate plus the quote label's height. What I'm seeing is some space being placed between the two labels, that depending on the length of the quote, changes size. Smaller quotes have more space, while longer quotes have less space. Here's a quick diagram of what I'm seeing:
Note the gap between the red and blue boxes (which I've set up using layer.borderColor/borderWidth so I can see them in the app), is larger the shorter the quote is.
If anyone can sift through the code below and help point me towards exactly what's causing the discrepancy, I'd be really grateful. From what I can see, the author label should always be 35 pixels beneath the quote label's y + height value.
Just to confirm: everything is hooked up correctly in Interface Builder, etc. The content of the quote's getting in there fine, everything else works, so it's hooked up, that isn't the issue.
To clarify, my question is: Why is the gap between the labels changing dependant on the quote's length, and how can I get a stable, settable gap of 35 pixels correctly?
Here's the code I'm using to position the labels:
// Fill and format Quote Details
_quoteLabel.text = [NSString stringWithFormat:#"\"%#\"", _selectedQuote.quote];
_authorLabel.text = _selectedQuote.author;
[_quoteLabel setFont: [UIFont fontWithName: kScriptFont size: 28.0f]];
[_authorLabel setFont: [UIFont fontWithName: kScriptFontAuthor size: 30.0f]];
// Automatically resize the label, then center it again.
[_quoteLabel sizeToFitMultipleLines];
[_quoteLabel setFrame: CGRectMake(11, 11, 298, _quoteLabel.frame.size.height)];
// Position the author label below the quote label, however high it is.
[_authorLabel setFrame: CGRectMake(11, 11 + _quoteLabel.frame.size.height + 35, _authorLabel.frame.size.width, _authorLabel.frame.size.height)];
Here's my custom method for sizeToFitMultipleLines:
- (void) sizeToFitMultipleLines
{
if (self.adjustsFontSizeToFitWidth) {
CGFloat adjustedFontSize = [self.text fontSizeWithFont: self.font constrainedToSize: self.frame.size minimumFontSize: self.minimumScaleFactor];
self.font = [self.font fontWithSize: adjustedFontSize];
}
[self sizeToFit];
}
And here's my fontSizeWithFont:constrainedToSize:minimumFontSize: method:
- (CGFloat) fontSizeWithFont: (UIFont *) font constrainedToSize: (CGSize) size minimumFontSize: (CGFloat) minimumFontSize
{
CGFloat fontSize = [font pointSize];
CGFloat height = [self sizeWithFont: font constrainedToSize: CGSizeMake(size.width, FLT_MAX) lineBreakMode: NSLineBreakByWordWrapping].height;
UIFont *newFont = font;
// Reduce font size while too large, break if no height (empty string)
while (height > size.height && height != 0 && fontSize > minimumFontSize) {
fontSize--;
newFont = [UIFont fontWithName: font.fontName size: fontSize];
height = [self sizeWithFont: newFont constrainedToSize: CGSizeMake(size.width, FLT_MAX) lineBreakMode: NSLineBreakByWordWrapping].height;
};
// Loop through words in string and resize to fit
for (NSString *word in [self componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]) {
CGFloat width = [word sizeWithFont: newFont].width;
while (width > size.width && width != 0 && fontSize > minimumFontSize) {
fontSize--;
newFont = [UIFont fontWithName: font.fontName size: fontSize];
width = [word sizeWithFont: newFont].width;
}
}
return fontSize;
}
After you called size to fit on both labels, calculate the distance between their frames and change them accordingly:
[quoteLabel sizeToFit];
[authorLabel sizeToFit];
float distance = authorLabel.frame.origin.y - quoteLabel.frame.size.height;
float difference = distance - 35;
authorLabel.frame = CGRectMake(authorLabel.frame.origin.x,(authorLabel.frame.origin.y - difference),authorLabel.frame.size.width,authorLabel.frame.size.height);
The reason the gap changes is that the quote label frame changes its height dependent on its content when you call sizeToFit.
UPDATE
Given the recent developments in the comments, I think you have 3 possibilities:
resize the whitespace instead of only the words, so that the string
actually fits in the frame correctly
somehow access the CTFramesetter of UILabel to see what the actual
frame, when all is said and done, amounts to
make your own UIView subclass that handles Core Text drawing in its
draw rect method (should be easy in your case), since after all you
are trying to give to UILabel a behavior that it's not meant for
It probably is moving where you want it, but then an auto-layout constraint or a spring/strut is moving it afterwards.
EDIT:
My first thought (which I ruled out because you said that the box around the words was the label frame. In later comments, you say that this is not an actual screen shot, but just a representation of it, so it could still be correct) was that you are doing this wrong:
[_quoteLabel sizeToFitMultipleLines];
[_quoteLabel setFrame: CGRectMake(11, 11, 298, _quoteLabel.frame.size.height)];
In the first line, you are sizing the text to fit in whatever the current width of the label might be, and then you turn around in the second line and change the width of the label. So most likely, what is happening is that you are sizing the label for some smaller width, which makes it tall. You then make the label wider than it was before and the text expands to fit the wider label, leaving a blank area beneath the actual text, although the frame has not changed. This makes the space betwee the labels exactly 35 as you want, however the top label's text does not go all of the way to the bottom of its frame so the white space is more than you want. Basically, you have this:
*************
* text text *
* text text *
* *
* *
* *
*************
*************
* text text *
*************
If this is the case, then you would fix it by setting the width first, like this:
// You could put anything for the 200 height since you will be changing it in the next line anyway.
[_quoteLabel setFrame: CGRectMake(11, 11, 298, 200];
[_quoteLabel sizeToFitMultipleLines];
I ended up solving the problem by using a single UILabel, and CoreText with an NSAttributedString. Kind of a cop-out, but it works.

Vertically Align UILabel text with constraints and no wrap (auto layout, single line)

So I have my view setup in IB such that this text label aligns with the top of the thumbnail via constraints.
However as we know, you can't vertically align text in a UILabel. My text updates the font size based on the length of the content. Full size text looks great, while small text is significantly lower on the view.
The existing solution involves either calling sizeToFit or updating the frame of the uilabel to match the height of the text. Unfortunately the latter (albeit ugly) solution doesn't play well with constraints where you aren't supposed to update the frame. The former solution basically doesn't work when you need to have the text autoshrink until it truncates. (So it doesn't work with a restricted number of lines and autoshrink).
Now as to why the intrinsic size (height) of the uilabel doesn't update like the width does when it's set to it's natural size via "Size to fit content" is beyond me. Seems like it definitely should, but it doesn't.
So I'm left looking for alternative solutions. As far as I can see, you might have to set a height constraint on the label, and adjust the height constant after calculating the height of the text. Anyone have a good solution?
This problem is a real PITA to solve. It doesn't help that the API's that work are deprecated in iOS7, or that the iOS7 replacement API's are broken. Blah!
Your solution is nice, however it uses a deprecated API (sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:), and it's not very well encapsulated - you need to copy this code around to any cells or views where you want this behavior. On the plus side it's fairly efficient! One bug may be that the label hasn't been laid out yet when you do your calculation, but you perform your calculation based on its width.
I propose that you encapsulate this behavior in a UILabel subclass. By placing the sizing calculation in an overridden intrinsicContentSize method the label will auto-size itself. I wrote the following, which incorporates your code that will execute on iOS6, and my version using non-deprecated API's for iOS7 or better:
#implementation TSAutoHeightLabel
- (CGSize) intrinsicContentSize
{
NSAssert( self.baselineAdjustment == UIBaselineAdjustmentAlignCenters, #"Please ensure you are using UIBaselineAdjustmentAlignCenters!" );
NSAssert( self.numberOfLines == 1, #"This is only for single-line labels!" );
CGSize intrinsicContentSize;
if ( [self.text respondsToSelector: #selector( boundingRectWithSize:options:attributes:context: )] )
{
NSStringDrawingContext* context = [NSStringDrawingContext new];
context.minimumScaleFactor = self.minimumScaleFactor;
CGSize inaccurateSize = [self.text boundingRectWithSize: CGSizeMake( self.bounds.size.width, CGFLOAT_MAX )
options: NSStringDrawingUsesLineFragmentOrigin
attributes: #{ NSFontAttributeName : self.font }
context: context].size;
CGSize accurateSize = [self.text sizeWithAttributes: #{ NSFontAttributeName : [UIFont fontWithName: self.font.fontName size: 12.0] } ];
CGFloat accurateHeight = accurateSize.height * inaccurateSize.width / accurateSize.width;
intrinsicContentSize = CGSizeMake( inaccurateSize.width, accurateHeight);
}
else
{
CGFloat actualFontSize;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
[self.text sizeWithFont: self.font
minFontSize: self.minimumFontSize
actualFontSize: &actualFontSize
forWidth: self.frame.size.width
lineBreakMode: NSLineBreakByTruncatingTail];
#pragma GCC diagnostic pop
CGRect lineBox = CTFontGetBoundingBox((__bridge CTFontRef)([UIFont fontWithName: self.font.fontName size: actualFontSize]));
intrinsicContentSize = lineBox.size;
}
return intrinsicContentSize;
}
#end
This implementation isn't perfect. I had to ensure using baselineAdjustment == UIBaselineAdjustmentAlignCenters, and I'm not 100% certain I understand why. And I'm not happy with the hoops I had to jump through to get an accurate text height. There's also a few pixel difference between what my calculation produces, and yours. Feel free to play with it and adjust as necessary :)
The boundingRectWithSize:options:attributes:context API seems pretty broken to me. While it (mostly!) correctly constrains the text to the input size, it doesn't calculate the correct height! The height it returns is based on the line-height of the supplied font, even if a scaling is in play. My guess is this is why UILabel doesn't have this behavior by default? My workaround is to calculate an unconstrained size where both the height and width are accurate, then use the ratio between the constrained and unconstrained widths to calculate the accurate height for the constrained size. What a PITA. There are lots of complaints in the Apple dev forums and here on SO that point out that this API has a number of issues like this.
So I found a workaround. It's a little dicey, but it works.
So what I did was add a height constraint to my line of text in IB, and grab a reference to that in my view.
Then in layoutSubviews, I update my constraint height based on the size of the font, which I have to calculate:
- (void)layoutSubviews {
if (self.titleLabel.text) {
CGFloat actualFontSize;
CGSize titleSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font minFontSize:9.0 actualFontSize:&actualFontSize forWidth:self.titleLabel.frame.size.width lineBreakMode:NSLineBreakByTruncatingTail];
CGRect lineBox = CTFontGetBoundingBox((__bridge CTFontRef)([UIFont fontWithName:#"ProximaNova-Regular" size:actualFontSize]));
self.titleHeightConstraint.constant = lineBox.size.height;
}
[super layoutSubviews];
}
At first I was just setting it to the actual font size, but even with an adjustment (*1.2) it was still clipping the smaller font sizes. The key was using CTFontGetBoundingBox with the font size determined from my calculation.
This is pretty unfortunate, and I'm hoping there's a better way. Perhaps I should switch to wrapping.
TomSwift thanks for your answer, i really struggled with this issue.
If someone is still getting weird behaviour, i had to change:
intrinsicContentSize = CGSizeMake( inaccurateSize.width, accurateHeight);
to
intrinsicContentSize = CGSizeMake( inaccurateSize.width, accurateHeight * 2);
then it worked like charm.
What you're looking for is these two lines of code.
myLabel.numberOfLines = 0;
myLabel.lineBreakMode = UILineBreakModeWordWrap;
and you will also find this in the Attributes Inspector under "Line Breaks" and "Lines".

Determine Font Size After Autoshrink

I have 2 UILabels for a scorekeeping app (Home and Away). The user can tap on Home or Away and change the label to be whatever they like. This is all working fine. When a user enters a name larger than the label size it will shrink the font to fit. This makes the 2 labels no longer match in font size, and doesn't look right. My question: How can you set the font size of one label to the size of another label that has been "autoshrunk"?
I also realize I will need to write code to determine which font size is smaller between the two labels and set them both to that number. I don't think I will have a problem with that, as long as I get an answer to the above question. It seems like it should be simple, but it has so far eluded me.
So I hope you know the frame size of both the labels.
Use – sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode: to find the minimum font size that it would use.
If you have any doubt, please let me know.
For me this worked fine:
- (CGFloat)actualTitleFontSize
{
NSStringDrawingContext *labelContext = [NSStringDrawingContext new];
labelContext.minimumScaleFactor = 0.2;
NSAttributedString *attributedString =
[[NSAttributedString alloc] initWithString:label.text attributes:#{NSFontAttributeName : label.font}];
[attributedString boundingRectWithSize:label.frame.size
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
context:labelContext];
CGFloat actualFontSize = label.font.pointSize * labelContext.actualScaleFactor;
return actualFontSize;
}

sizeToFit doesn't trigger new line with long words

I just ran into to strange problem, I have a custom tableview cell with a dynamic height.
While testing this all seemed to work fine, but now that I'm loading real content into it there seem to be some problems.
It appears that some text doesn't trigger a new line in a UILabel
Correct: http://dl.dropbox.com/u/274185/Screen%20Shot%202012-05-09%20at%201.15.21%20PM.png
Wrong: http://dl.dropbox.com/u/274185/Screen%20Shot%202012-05-09%20at%201.15.30%20PM.png
As you can see in the wrong example, the text is pushed to the second line, but the height of the label still only counts one line.
item.project = #"Another Test Project With Longer Title (Admin / Project Management)";
item.project = #"Test Project (Admin / Project Management)";
The way I calculate the height is like this:
// when creating the cell
cell.projectLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.projectLabel.numberOfLines = 0;
[cell.projectLabel sizeToFit];
// in heightForRowAtIndexPath()
CGSize projectHeight = [item.project sizeWithFont:[UIFont boldSystemFontOfSize:13.0f] constrainedToSize:CGSizeMake(320.0f, CGFLOAT_MAX) lineBreakMode: UILineBreakModeWordWrap];
I tried changing the lineBreakMode, but this doesn't seem to help much
EDIT:
It appeared to be a problem when calculation the height of the text, I used a fixed 320 points, which isn't correct, after using the actual width the height was calculated correctly.
CGSize projectHeight = [item.project sizeWithFont:[UIFont boldSystemFontOfSize:13.0f] constrainedToSize:CGSizeMake(cell.projectLabel.bounds.size.width, CGFLOAT_MAX) lineBreakMode: UILineBreakModeWordWrap];
I believe that sizeToFit only sizes the view down.
You should set the frame of your label to be high enough for two lines and then call sizeToFit. That will shrink the label when the text is only one line but keep its height when the text is two lines.

Resources