设置minimumScaleFactor时,UILabel会获得当前的比例因子吗?

时间:2015-07-14 19:59:17

标签: ios objective-c swift uilabel

我有UILabel并设置:

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

设置标签文字后,我想知道当前的比例因子是什么。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

您还需要知道原始字体大小是多少,但我想您可以通过某种方式找到它

也就是说,使用以下函数来发现实际的字体大小:

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)

答案 1 :(得分:0)

您可以通过以下方式解决此问题:

快速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
    } 
}

用法:

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

或者,如果您有兴趣在缩小后同步多个标签的字体大小,那么我在这里https://stackoverflow.com/a/58376331/9024807