【发布时间】:2015-07-14 19:59:16
【问题描述】:
我有一个UILabel 并设置:
let label = UILabel()
label.minimumScaleFactor = 10 / 25
设置标签文本后,我想知道当前的比例因子是多少。我该怎么做?
【问题讨论】:
标签: ios objective-c swift uilabel
我有一个UILabel 并设置:
let label = UILabel()
label.minimumScaleFactor = 10 / 25
设置标签文本后,我想知道当前的比例因子是多少。我该怎么做?
【问题讨论】:
标签: ios objective-c swift uilabel
您还需要知道原始字体大小是多少,但我想您可以通过某种方式找到它?
也就是说,使用下面的函数来发现实际的字体大小:
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)
【讨论】:
actualScaleFactor 对我来说始终是 1。
你可以这样解决这个问题:
斯威夫特 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
【讨论】: