I have a UILabel and it is set to 42.0 pt font, and the width of the label is set using autoconstraints based on factors other than the label itself (aka the things to the right
Swift 5
func setFontForLabel(label:UILabel, maxFontSize:CGFloat, minFontSize:CGFloat, maxLines:Int) {
var numLines: Int = 1
var textSize: CGSize = CGSize.zero
var frameSize: CGSize = CGSize.zero
let font: UIFont = label.font.withSize(maxFontSize)
frameSize = label.frame.size
textSize = (label.text! as NSString).size(withAttributes: [NSAttributedString.Key.font: font])
// Determine number of lines
while ((textSize.width/CGFloat(numLines)) / (textSize.height * CGFloat(numLines)) > frameSize.width / frameSize.height) && numLines < maxLines {
numLines += 1
}
label.font = font
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = numLines
label.minimumScaleFactor = minFontSize/maxFontSize
}
Swift 3
I looked at the post that paper111 posted. Unfortunately it's in Obj-C and the sizeWithFont: ,constrainedToSize: , lineBreakMode:
method has been deprecated. (- - );
His answer was good, but still didn't provide a fixed size. What I did was to start with a UILabel
that had everything but the height (this is probably the same for most people).
let myFrame = CGRect(x: 0, y:0, width: 200, height: self.view.height)
let myLbl = UILabel(frame: myFrame)
let finalHeight:CGFloat = 300
myLbl.font = UIFont(name: "Chalkduster", size: 16.0)
myLbl.lineBreakMode = .byWordWrapping
myLbl.numberOfLines = 0
myLbl.text = "Imagine your long line of text here"
addSubview(myLbl)
myLbl.sizeToFit()
guard myLbl.frame.height > finalHeight else { return }
var fSize:CGFloat = 16 //start with the default font size
repeat {
fSize -= 2
myLbl.font = UIFont(name: "Chalkduster", size: fSize)
myLbl.sizeToFit()
} while myLbl.frame.height > finalHeight
You can see that there's a guard
blocking the resize if it's not needed. Also, calling sizeToFit()
many times isn't ideal, but I can't think of another way around it. I tried to use myLbl.font.withSize(fSize)
in the loop but it wouldn't work, so I used the full method instead.
Hope it works for you!