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?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With