UILabel 在设置 minimumScaleFactor 时获取当前比例因子?
Posted
技术标签:
【中文标题】UILabel 在设置 minimumScaleFactor 时获取当前比例因子?【英文标题】:UILabel get current scale factor when minimumScaleFactor was set? 【发布时间】:2015-07-14 19:59:16 【问题描述】:我有一个UILabel
并设置:
let label = UILabel()
label.minimumScaleFactor = 10 / 25
设置标签文本后,我想知道当前的比例因子是多少。我该怎么做?
【问题讨论】:
【参考方案1】:您还需要知道原始字体大小是多少,但我想您可以通过某种方式找到它?
也就是说,使用下面的函数来发现实际的字体大小:
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
。
对我来说这个参数也是1【参考方案2】:
你可以这样解决这个问题:
斯威夫特 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://***.com/a/58376331/9024807
【讨论】:
以上是关于UILabel 在设置 minimumScaleFactor 时获取当前比例因子?的主要内容,如果未能解决你的问题,请参考以下文章
在UITableview swift中使用UILabel和UIWebView设置heightForRow
如何以编程方式在 UILabel 上设置 sizeToFit 宽度和高度?