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

后端 未结 5 2771
眼角桃花
眼角桃花 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:36

    Swift 5

    extension UILabel{
    func adjustsFontSizeToFit(maxFontSize:CGFloat,width:CGFloat,height:CGFloat) {
        self.numberOfLines = 0
        var fontSize:CGFloat = maxFontSize
        if self.sizeThatFits(CGSize(width: width, height: .infinity)).height > height{
            while self.sizeThatFits(CGSize(width: width, height: .infinity)).height > height{
                fontSize -= 1
                self.font = self.font.withSize(fontSize)
            }
        }
    }
    

    }

提交回复
热议问题