Determine UILabel height for centering when using adjustFontSizeToFitWidth - ios

I have the following cell design where the numeric label shrinks and the "Overall" label is directly underneath.
I have properly set the adjustFontSizeToFitWidth and minimumFontSize properties. The font is resizing correctly. However, anchoring the numeric label to the bottom is challenging. Particularly when the font shrinks the gap between the two labels widens and does not appear vertically centered.
I have tried sizeToFit, sizeThatFits, and using the font's pointSize. All unsuccessfully.
I am aware of sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:, but don't understand why I would need it in combination with adjustFontSizeToFitWidth.

Ah, so you want to position the UILabels in the middle of the container view (both horizontally and vertically)?
I have rephrased my answer so it will make more sense to future readers.
My code is assuming that you have the 3 IBOutlets set up:
UIView *containerView; //Your nice view containing the two textfields.
UILabel *points; //The label containing the number.
UILabel *overall; //The textfield containing the text 'overall'.
You could simply set the frame of the labels after assigning the text and calling the sizeToFit.
This first line positions the UILabel points, the only change being that the y coordinate is half of containerView subtract half of the height of itself.
points.frame = CGRectMake(points.frame.origin.x, (containerView.frame.size.height / 2) - (points.frame.size.height / 2), points.frame.size.width, points.frame.size.height);
To position the overall accordingly - say there is a distance of say 6 between the number and overall labels:
int space = 6;
overall.frame = CGRectMake(overall.frame.origin.x, points.frame.origin.y + points.frame.size.height + space, overall.frame.size.width, overall.frame.size.height);
Having read your comments, I think you are after this solution. If you want both UILabels to appear in the middle; subtract (overall.frame.size.height / 2) + (space / 2) from the y value of points like so (with the code of number 2 beneath it):
int space = 6;
points.frame = CGRectMake(points.frame.origin.x, ((containerView.frame.size.height / 2) - (points.frame.size.height / 2)) - ((overall.frame.size.height / 2) + (space / 2)), points.frame.size.width, points.frame.size.height);
overall.frame = CGRectMake(overall.frame.origin.x, points.frame.origin.y + points.frame.size.height + space, overall.frame.size.width, overall.frame.size.height);
The final point will produce an output like this image. As you can see the blue line is half of the whole image, and intersects the black rectangle (which is snuggly around the two labels) at its middle point. I hope this is what you were after.

Instead of using two labels, use CATextLayer instead. You will be easily able to make one part BOLD and the other normal. plus position and adjusting size for One layer will be easy relative to placing two labels. shadow setting, line break mode, fonts you will be able to adjust everything beautifully :)

Related

Find the lowest positioned element

I'm trying to make constraints via Snapkit in a table view cell but my problem is I need to find out which element has max y position (The lowest one).
I have an UIImageView and next to image view UILabel elements. The label text is dynamic and could be very long or very short. Below these 2 elements, I have another one that should be aligned based on the label height, either taking image view or label.
My question is how to find which element (UIIMageView, UILabel) has a bigger Y position.
To be more clear I attached a draw with simple two cases.
Set a greaterThanOrEqualTo constraint on both elements.
In "plain language":
AnotherElement.top >= ImageView.Bottom (with constant of 12, or however much space you want)
AnotherElement.top >= Label.Bottom (with constant of 12, or however much space you want)

How to vertically center text in UILabel with programmatic constraints after height constraint addition

I have a UILabel that I'm using inside a container view. I'm using AutoLayout entirely programmatically--no xib or storyboard. My UILabel constraints (no height constraint set, large fixed width, top and left edges pinned, numberOfLines = 0, bottom of superview pinned to bottom of label) work perfectly for normal (around 13 or 14 point) sized text, but at large (60 point) size text I started noticing large gaps of extra space above and below my character; in this case, the capital letter "S" that's an NSMutableAttributedString. The only attributes for this attributed string are the font name and a kerning value of 1.0. Below picture shows a magnified screenshot of my label from Pixie (white square shown is from that program) with my UILabel's backgroundColor in red:
After doing lots of research (Ignore Ascender and Descender when centering UILabel vertically?, iOS - Get the "real" height of a letter, Vertically center text in UILabel depending on actual visible letter height), it seemed the reason I was encountering this issue was because of the ascender and descender values for this font aren't getting used in this case (this is a capital "S," so it would seem I just need its capHeight value). So, I decided to constrict my label height to this value, and did so by setting a height constraint equal to its capHeight value after the "S" attributed text is set. Doing this produced the following image:
As you can see, the text is now clipped in the label. As a sort of hack, I figured I'd add some padding to counteract this, so multiplying my capHeight value by 1.1 yielded the following image:
That's fine for some padding, but now there's 4 px of extra space at the top. Granted I'm zoomed in very far, but I'm not sure why I'm seeing this—I would think that since the height constraint is set to the height of this capHeight value (which has some extra added for padding now) that the "S" would be vertically centered. I've tried calling setNeedsLayout on the label, but that didn't do anything. These are the things I would love to know:
Why is the capHeight value either not returning the correct value and/or setting the label's height constraint to this value is causing the text to get clipped?
Why do I need to add padding to the capHeight value?
Does anyone have any suggestions on how I can get this text vertically centered after I add padding and/or why it's not happening automatically? I saw this answer (https://stackoverflow.com/a/17376146/482557) but wasn't sure if that would apply here.
Thanks!

UILabel wont fill two lines if needed

I have a UILabel in a collection view cell that is center aligned with number of lines = 0 and line breaks = word wrap
My text is dynamic, dependent upon requested data, so some cell's don't need two lines.
Any idea why it still wont go to the second line if needed? Getting stuck on this.
While I do not know because I do not see any code, I suggest looking at the size of the label. Are you sure the label is not getting stretched / set to a size larger then the collectionviewcell?
I think this is what you're experiencing:
I made two labels, each with:
number of lines = 0
word wrap activated
just enough x and y constraints to keep them in place on the view!
I think this is what you want:
I added constraints to each label making their width less than or equal to 300

Ignore Ascender and Descender when centering UILabel vertically?

I’m using AutoLayout to position some labels in the vertical centre of a cell. The text is in all-caps, but the UILabel in question, even when sizeToFit is applied, leaves space below the text, which looks a lot like it would be for the tails on letters such as a lower case y, p, and q. Since I’m centring vertically, this is causing an offset and meaning the text appears a few pixels higher than it should do.
Another question may be: can I have a font intelligently adjust its vertical centre dependant on whether it contains any characters which use the ascender or descender?
For instance, the string “abbaba” doesn’t need the descender, whereas the string “oyyoyo” doesn’t need the ascender. Strings in all-caps also never need the descender. If I vertically center “oyyoyoyo” it’ll appear too low.
Thanks, Abhinit, for your answer.
I was also looking for this so I would like to post here the exact constraints you need to apply to align texts to your liking.
This image from Wikipedia shows the different size sections of a font.
So, there are many ways to align a label depending on whether you want to align to the ascender height, the cap height, the x-height, baseline or descender height.
Let's say you have a label containing text in caps like "HELLO" and you want to align with viewAbove to cap height and align with viewBelow to baseline.
You would do:
let font = label.font
let ascenderDelta = font.ascender - font.capHeight
LayoutHelper()
.addViews([
"label":label, "viewAbove":viewAbove, "viewBelow":viewBelow
])
.withMetrics(["ascenderDelta":ascenderDelta])
.addConstraints([
// -- Here the constraints to align to cap height --
"X:label.top == viewAbove.bottom - ascenderDelta",
"X:label.baseline == viewBelow.top",
...other constraints...
])
Note: in the example I'm using my utility class LayoutHelper, but I hope the idea is clear.
About an "auto-aligning" label:
I will think about making an "intelligent" label that adjusts to the appropriate line depending on whether it contains descenders, ascenders, caps, etc.
You could do it using negative insets in drawTextInRect(like here but, for example, using insets = {-ascenderDelta, 0, font.descender, 0}). But that would crop any ascenders/descenders in case you had. I would prefer to align to caps without cropping any possible ascender.
You can use the 'capHeight' and 'xHeight' properties on UIFont to get the correct height and use that to size the UILabel.
Of course this assumes that you know for sure if a string would be lowercase or uppercase only. If not, then you can override setText on a UILabel and check every time the function gets called.
I would also think of looking deeper into CoreText and implementing something like this http://www.zsiegel.com/2012/10/23/Core-Text-Calculating-line-heights/
I had the same problem and solved it by subclassing UILabel and changing its draw method:
- (void)drawRect:(CGRect)rect
{
CGRect capCenteredRect = CGRectMake(rect.origin.x, (self.font.leading-self.font.capHeight)*0.5f, rect.size.width, rect.size.height);
[super drawTextInRect:capCenteredRect];
}
In my case I needed to center to caps because the vertical centering of the UILabel is always some pixels off.
If you need to center vertically to lower case letters with descender you can change the rect to:
CGRectMake(rect.origin.x, (self.font.leading-self.font.xHeight)*0.5f+self.font.descender, rect.size.width, rect.size.height)

vertically center UILabel between two other lables

I have 3 UILabels drawn in storyboard positioned on top of each other.
Static UI Label 1
Dynamic UI Label 2
Static UI Label 3
Labels 1 and 3 are static and never change. Label 2 is dynamic and is always one sentence long, but could be a short or long sentence that wraps. I want Label 2 to be perfectly vertically centered between label 1 and label 3 based on how much text is there. Any ideas how to do this? Greatly appreciated!
If you're using auto layout (which is on by default), then you can just stretch the middle label until it's top and bottom are the standard distance away from the other two labels (you will see a dotted blue line when you reach that distance). This assumes that your label has a clear background, or that you don't mind seeing a tall label if it doesn't. The text will be centered vertically in this tall label regardless of the number of lines. It will also stay centered on rotation.
Add the center values of Label1 and Label3 , Divide it by 2 and make it center of label2
CGPoint point = CGPointMake(Label2.Center.x,(Label1.center.y+Label3.center.y)/2);
Label2.center = point;
That's all....

Resources