Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel does not autoshrink

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

num lines 1 on 3.5"num lines 0 on 3.5"num lines 1 on 4.0"num lines 0 on 4.0"

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.

like image 576
user1927638 Avatar asked Aug 07 '14 18:08

user1927638


2 Answers

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.

like image 80
Jeffrey Sun Avatar answered Nov 13 '22 16:11

Jeffrey Sun


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)
        }
    }
}
like image 5
Rivera Avatar answered Nov 13 '22 16:11

Rivera