什么时候调整.FontSizeToFitWidth或boundingRectWithSize更改context.actualScaleFactor?

时间:2016-01-05 22:36:39

标签: ios swift uilabel font-size drawingcontext

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的步骤是什么?

2 个答案:

答案 0 :(得分:0)

与@RanLearns相同的问题。

添加myButton.titleLabel!.minimumScaleFactor = 0.1后,它对我有用

答案 1 :(得分:-1)

在viewDidAppear中执行此操作...这对我有用