11

I have a UILabel and set:

let label = UILabel()
label.minimumScaleFactor = 10 / 25

After setting the label text I want to know what the current scale factor is. How can I do that?

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
Sven Bauer
  • 1,619
  • 2
  • 13
  • 22

2 Answers2

4

You also need to know what is the original font size, but I guess you can find it in some way

That said, use the following func to discover the actual font size:

func getFontSizeForLabel(_ label: UILabel) -> CGFloat {
    let text: NSMutableAttributedString = NSMutableAttributedString(attributedString: label.attributedText!)
    text.setAttributes([NSFontAttributeName: label.font], range: NSMakeRange(0, text.length))
    let context: NSStringDrawingContext = NSStringDrawingContext()
    context.minimumScaleFactor = label.minimumScaleFactor
    text.boundingRect(with: label.frame.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: context)
    let adjustedFontSize: CGFloat = label.font.pointSize * context.actualScaleFactor
    return adjustedFontSize
}

//actualFontSize is the size, in points, of your text
let actualFontSize = getFontSizeForLabel(label)

//with a simple calc you'll get the new Scale factor
print(actualFontSize/originalFontSize*100)
carmine
  • 1,597
  • 2
  • 24
  • 33
2

You can solve this problem this way:

Swift 5

extension UILabel {
    var actualScaleFactor: CGFloat {
        guard let attributedText = attributedText else { return font.pointSize }
        let text = NSMutableAttributedString(attributedString: attributedText)
        text.setAttributes([.font: font as Any], range: NSRange(location: 0, length: text.length))
        let context = NSStringDrawingContext()
        context.minimumScaleFactor = minimumScaleFactor
        text.boundingRect(with: frame.size, options: .usesLineFragmentOrigin, context: context)
        return context.actualScaleFactor
    } 
}

Usage:

label.text = text
view.setNeedsLayout()
view.layoutIfNeeded()
// Now you will have what you wanted
let actualScaleFactor = label.actualScaleFactor

Or if you are interested in synchronizing the font size of several labels after shrinking, then I answered here https://stackoverflow.com/a/58376331/9024807

Nikaaner
  • 1,022
  • 16
  • 19