Swift 3 - Adjust Font Size to Fit Width, Multiple Lines

后端 未结 5 2700
眼角桃花
眼角桃花 2021-02-20 13:53

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

5条回答
  •  Happy的楠姐
    2021-02-20 14:37

    @Krunal's answer helped me but it doesn't work when you have unknown number of lines so here's the solution I came up with. You can also set the maximum and minimum font size. Hope this helps someone!

    Swift 2.2 - Sorry, haven't migrated to Swift 3 yet.

    func setFontForLabel(label:UILabel, maxFontSize:CGFloat, minFontSize:CGFloat, maxLines:Int) {
    
        var numLines: Int = 1
        var textSize: CGSize = CGSizeZero
        var frameSize: CGSize = CGSizeZero
        var font: UIFont = UIFont.systemFontOfSize(maxFontSize)
    
        frameSize = label.frame.size
    
        textSize = (label.text! as NSString).sizeWithAttributes([NSFontAttributeName: 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
    }
    

提交回复
热议问题