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

后端 未结 5 2705
眼角桃花
眼角桃花 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条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-20 14:37

    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!

提交回复
热议问题