How to adjust font size to fit UILabel height and width

I have a UILabel square (yellow) that contains one letter.

enter image description here

I used the following code from this SO answer to adjust the font size so that it fits in UILabel :

 letterLabel.font = UIFont(name: letterLabel.font.fontName, size: 100) letterLabel.adjustsFontSizeToFitWidth = true letterLabel.textAlignment = NSTextAlignment.Center 

As you can see in the screenshot, the font size corresponds to the width. But since the text is only one letter, therefore, we must also look at the height. How can we adjust the font size so that the height is also within UILabel ?

+6
source share
4 answers

I did not find a simple solution, so I made this extension:

 extension UILabel { func setFontSizeToFill() { let frameSize = self.bounds.size guard frameSize.height>0 && frameSize.width>0 && self.text != nil else {return} var fontPoints = self.font.pointSize var fontSize = self.text!.size(withAttributes: [NSAttributedStringKey.font: self.font.withSize(fontPoints)]) var increment = CGFloat(0) if fontSize.width > frameSize.width || fontSize.height > frameSize.height { increment = -1 } else { increment = 1 } while true { fontSize = self.text!.size(withAttributes: [NSAttributedStringKey.font: self.font.withSize(fontPoints+increment)]) if increment < 0 { if fontSize.width < frameSize.width && fontSize.height < frameSize.height { fontPoints += increment break } } else { if fontSize.width > frameSize.width || fontSize.height > frameSize.height { break } } fontPoints += increment } self.font = self.font.withSize(fontPoints) } } 
0
source

I needed only one letter to indicate on the label (initial name), so the requirement was clear, it had to scale to fit the height.

Decision:

 class AnyView : UIView{ private var nameLabel:UILabel! = nil override func layoutSubviews() { super.layoutSubviews() //Considering the nameLabel has been already created and added as subview with all the constraint set nameLabel.font = nameLabel.font.withSize(nameLabel.bounds.height * 0.6/*The factor can be adjusted as per need*/) } } 
0
source

I checked your code is working fine for me. enter image description here

I think cell height is a problem, and I did not give cell height. Try to remove cell height

0
source

Try [label sizeToFit] or [label sizeThatFits:(CGSize)]

-3
source

Source: https://habr.com/ru/post/1241266/


All Articles