How to scale the fonts in a Button

2019-06-03 03:43发布

I'm trying to complete my first app in Swift and I met with the problem. I have some buttons with the tittles and background image. Running the simulation on different devices makes them scale, so the tittles goes out of buttons frame. There is no "Dynamic Type Automatically Adjust Font" checkbox in my Xcode attributes inspector so I made the custom UIButton class and made the inspectable var

@IBInspectable var adjustFontSize : Bool {
    set { titleLabel?.adjustsFontForContentSizeCategory = newValue } 
    get { return titleLabel!.adjustsFontForContentSizeCategory  }

but this does't helps and I got "Automatically adjusts font requires using a dynamic type text style" warning

So how can I make my button title scale to fit the Button frame when the button changes size and proportions on different devices?

2条回答
Luminary・发光体
2楼-- · 2019-06-03 04:22

Try these

button.titleLabel!.numberOfLines = 1
button.titleLabel!.adjustsFontSizeToFitWidth = true
button.titleLabel!.baselineAdjustment = .alignCenters

but for them to work, you will have to set button width constraint either in storyboard or programatically.

This will then make the title size change based on the width of the button.

查看更多
手持菜刀,她持情操
3楼-- · 2019-06-03 04:47

This worked for me.

 btn.titleLabel?.minimumScaleFactor = 0.1
 btn.titleLabel?.numberOfLines = 1
 btn.titleLabel?.adjustsFontSizeToFitWidth = true
查看更多
登录 后发表回答