NSStringDrawingContext的ActualScaleFactor何时更改?

The documentation says:

“如果在minimumScaleFactor属性中指定了自定义值,则在绘制完成后,此属性将包含用于绘制字符串的实际比例因子值。”

我的代码:

myButton.titleLabel!.font = UIFont(name: "AmericanTypewriter-Bold", size: 40)
myButton.titleLabel?.adjustsFontSizeToFitWidth = true
myButton.setTitle("\(textString)", forState: .Normal)

let attributes = [NSFontAttributeName : myButton.titleLabel!.font]
let attributedString = NSMutableAttributedString(string:textString, attributes:attributes)

let context = NSStringDrawingContext()
context.minimumScaleFactor = myButton.titleLabel!.minimumScaleFactor

print("context: \(context.actualScaleFactor)")

let resultingRect = attributedString.boundingRectWithSize(myButton.titleLabel!.bounds.size, options: .UsesLineFragmentOrigin, context: context)

print("actual context after drawing: \(context.actualScaleFactor)")

//want to get the font size after adjustsFontSizeToFitWidth has done its magic:
//let actualFontSize = myButton.titleLabel!.font.pointSize * context.actualScaleFactor

不会被缩小而适合的文本和为适应标签的宽度而调整的较长文本的控制台日志都相同:
context: 0.0
actual context after drawing: 1.0

知道将文本大小调整为适合标签大小后,要从上下文中获取真实的scaleFactor时,我还缺少什么步骤?

最佳答案

在viewDidAppear中做到这一点...对我有用

10-01 17:41