Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel get current scale factor when minimumScaleFactor was set?

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?

like image 544
Sven Bauer Avatar asked Jul 14 '15 19:07

Sven Bauer


2 Answers

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)
like image 103
carmine Avatar answered Nov 03 '22 08:11

carmine


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

like image 40
Nikaaner Avatar answered Nov 03 '22 07:11

Nikaaner