UILabel get current scale factor when minimumScaleFactor was set?
Asked Answered
F

2

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?

Floccus answered 14/7, 2015 at 19:59 Comment(0)
C
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)
Crazyweed answered 23/11, 2016 at 16:43 Comment(3)
actualScaleFactor is always 1 for me.Agle
For me this parameter is 1 tooCrab
@lulian-onofrei Did you try setting number of lines = 1Delvalle
L
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://mcmap.net/q/153231/-autolayout-link-two-uilabels-to-have-the-same-font-size

Landlord answered 11/10, 2019 at 11:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.