0

I have a header label which I am adjusting the font size of, to fit to the size of the label. I would like to store the value of that font size so I can set the font size of some buttons to it.

I have tried to just store the pointSize of the label, but that just gives me the unadjusted value, not the value that is actually in effect.

The reason for this is, that I want the size of all the text in labels and buttons to look good on different sized iPad screens. But I am struggling with keeping the size the same, across multiple elements.

class ViewController: UIViewController {
    @IBOutlet weak var essenceButton: UIButton!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var tribesButton: UIButton!

    @IBOutlet weak var creaturesButton: UIButton!
    @IBOutlet weak var monstersButton: UIButton!
    @IBOutlet weak var musesButton: UIButton!
    @IBOutlet weak var newsletterButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.titleLabel.adjustsFontSizeToFitWidth = true

        let fontsize = self.titleLabel.font.pointSize

        self.essenceButton.titleLabel?.font = essenceButton.titleLabel?.font.withSize(fontsize)

        self.tribesButton.titleLabel?.font = tribesButton.titleLabel?.font.withSize(fontsize)
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Benedikt J Schlegel
  • 1,707
  • 1
  • 10
  • 23

1 Answers1

0

At viewDidLoad(), the view and its subviews (including the label) have not yet been laid out for the device's screen, so the label's font size has not changed.

You should be able to do this in viewWillLayoutSubviews():

override func viewWillLayoutSubviews() {
  super.viewWillLayoutSubviews()
  view.layoutIfNeeded()
  // Code to adjust font of the other UI items here
}
Rudedog
  • 4,323
  • 1
  • 23
  • 34
  • sadly I still get the same result. also tried viewDidLayoutSubviews(); but that also does not seem to work. – Benedikt J Schlegel Apr 10 '19 at 20:25
  • Ah yes. The answer to this https://stackoverflow.com/questions/2396715/how-to-figure-out-the-font-size-of-a-uilabel-when-adjustsfontsizetofitwidth-is should help you. If the label you're using for the source font has a dynamic size you'll still want to do it after the view has laid out its subviews. – Rudedog Apr 10 '19 at 22:04