skip to Main Content

I have a basic UIButton with the following constraints:

UIButton autolayout constraint dynamic text font size

I have some basic trailing and top constraints and I have a >= width and height constraint set to 48 as I want 48 to be my minimum width and height for the button.

My goal is to have the text in button grow as the user changes their font size from settings.

This text in the button seems to be increasing in size, however, the frame doesn’t seem to be updating to accomodate that increase.

enter image description here

This is what I mean setting the font size from control panel
Dynamic text font size control panel iOS Swift

However, if I quit the app and launch it again, the frame size is calculated correctly and on changing the text size from the control panel seems to make the font size in button shrink and grow appropriately.

UIButton frame size increase

It seems as if a max width / height needs to be determined first.

In the code I even set this:

skipButton.titleLabel?.font = UIFont.font(forTextStyle: .body, fontName: .suecaNanoRegular, size: 14)
skipButton.titleLabel?.adjustsFontForContentSizeCategory = true

How can I get my UIButton to support dynamic font sizes at run time.

Here are my other button settings if that helps with debugging.

UIButton settings storyboard dynamic text size font swift iOS

2

Answers


  1. The problem is that your font is not itself dynamic.

    Delete your code about the title label, and reconfigure the button in the storyboard to be Plain style instead of Default style, and give it a dynamic font setting, as shown in this screen shot:

    enter image description here

    The button title font size will then behave as you expect.

    enter image description here

    Login or Signup to reply.
  2. This seems to work for me…

    Add a button to Storyboard, change only 3 properties:

    • Style: Default
    • Title: Skip
    • Background: Yellow (so we can see the framing at run-time)

    Constraints:

    enter image description here

    enter image description here

    Added a random font to my project – "Gotham-BookItalic.otf"

    View Controller class:

    class DynamicFontVC: UIViewController {
        
        @IBOutlet var skipButton: UIButton!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            guard let customFont = UIFont(name: "Gotham-BookItalic", size: 14.0) else {
                fatalError("Could not load font!")
            }
            
            skipButton.titleLabel?.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: customFont)
            skipButton.titleLabel?.adjustsFontForContentSizeCategory = true
        }
        
    }
    

    Result:

    enter image description here


    Edit — with Control Alignment set to Trailing / Top:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search