如何以编程方式调整 UIButton 中文本的字体大小以适应 Swift 中的高度?

How to adjust font size of text in a UIButton to fit the height programmatically in Swift?

我有一个按钮,并设置它的框架和标题:

let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(x, y, width, height)
button.setTitle("Shuffle", forState: UIControlState.Normal)

我一直在使用下面的方法来更改 UIButton 中文本的宽度:

button.titleLabel?.adjustsFontSizeToFitWidth = true

这会将字体大小调整为按钮的宽度,但不会调整按钮的高度。我找不到等效的方法来确保文本也适合 UIButton 的高度。我也尝试了以下方法,但它对我不起作用:

button.titleLabel?.drawTextInRect(button.frame)

看看 UILabelbaselineAdjustment 属性:

它可以与 UIButton 一起使用,如下所示:

button.titleLabel?.baselineAdjustment = UIBaselineAdjustment.AlignCenters