How to figure out the font size of a UILabel when -adjustsFontSizeToFitWidth is set to YES?

后端 未结 5 2119
醉话见心
醉话见心 2020-11-30 05:33

When myLabel.adjustsFontSizeToFitWidth = YES, UILabel will adjust the font size automatically in case the text is too long for the label. For example, if my lab

5条回答
  •  自闭症患者
    2020-11-30 06:24

    Swift 5

    For one-line UILabel

    extension UILabel {
    
        var actualFontSize: CGFloat {
        //initial label
         let fullSizeLabel = UILabel()
         fullSizeLabel.font = self.font
         fullSizeLabel.text = self.text
         fullSizeLabel.sizeToFit()
    
         var actualFontSize: CGFloat = self.font.pointSize * (self.bounds.size.width / fullSizeLabel.bounds.size.width);
    
        //correct, if new font size bigger than initial
         actualFontSize = actualFontSize < self.font.pointSize ? actualFontSize : self.font.pointSize;
    
         return actualFontSize
        }
    
    }
    

    Getting the actual font size is then as simple as:

    let currentLabelFontSize = myLabel.actualFontSize
    

提交回复
热议问题