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?
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://mcmap.net/q/153231/-autolayout-link-two-uilabels-to-have-the-same-font-size
© 2022 - 2024 — McMap. All rights reserved.
actualScaleFactor
is always1
for me. – Agle