I am trying to create a view that scales a specific UILabel based on the height of its parent view. In the storyboard, I have the Autoshrink option set to "Minimum Font Size" to the value 8 and the number of lines to 1. However, I am noticing that if I have the number of lines set to 1, the font size does not adjust to fit. If I have the number of lines set to 0, autoshrink does occur, but the font size is smaller than the 147 size that I specified for the 4.0" display.
(Top): Left: num lines = 1, Right: num lines = 0 on a 3.5" display
(Bottom): Left: num lines = 1, Right: num lines = 0 on a 4.0" display
Ideally, I would like the 4.0" screen to have a font size of 147 and giving it the ability to scale down on a 3.5" display.
My understanding is that if you set numberOfLines
to 1
, the label will autoshrink based on width, not height. This should explain the top-left image.
As for the bottom-right image, I would try increasing the height of the label. It will autoshrink based on the intrinsic content size of the text, so it just seems that a font size of 147 has a content height that is currently taller than your label height in the taller screen.
Auto shrink only seems to apply when the width is smaller than needed and not when the height is insufficient.
I solved it with a custom subclass:
class HeightAutoShrinkingLabel: UILabel {
override func layoutSubviews() {
super.layoutSubviews()
while self.font.pointSize > 1 {
if self.intrinsicContentSize.height <= self.frame.height {
// Fits
break
}
self.font = self.font.withSize(font.pointSize - 1)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With