0

I have a multiline UILabel text which expands dynamically according to the text length. I have setup proper auto layout in storyboard and grows bigger if the text is lengthy.

But i want to reduce the font size to 24 if its 2-line and to 20 if its 3-line text.

If text is single line then, font size should be 34.

I tried minimum font scale = 20/34 = .58

but no use. Please suggest a solution

j.krissa
  • 223
  • 5
  • 21
  • Is this related to: https://stackoverflow.com/a/28742358/12783209? Or would you like to set a **precise** font size when the text grows too large? – The Swift Coder Apr 20 '21 at 23:14

1 Answers1

1

You could use a switch statement to determine the font size when a certain number of lines have been after changing the label's text.

Using the actualNumberOfLines() algorithm from https://stackoverflow.com/a/60993649/12783209 allows you to redeclare the font for this label whenever necessary.

func changeFontSizeIfNeeded(on label: inout UILabel){

switch label.actualNumberOfLines{
case 2:
 label.font = label.font.withSize(24)
case 3: 
 label.font = label.font.withSize(20)

default:
//Change this to be the default font size
  label.font = label.font.withSize(30)

}


}

And add this extension to your project:

extension UILabel{

func actualNumberOfLines()-> Int {
        // You have to call layoutIfNeeded() if you are using autoLayout
        self.layoutIfNeeded()

        let myText = self.text! as NSString

        let rect = CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: self.font as Any], context: nil)

        return Int(ceil(CGFloat(labelSize.height) / self.font.lineHeight))
    }

 }
The Swift Coder
  • 390
  • 3
  • 13