Nelson Matias
Nelson Matias

Reputation: 473

Swift how do you fit font size to custom frame?

I have a UIButton with size 50x50. How do I set the font size of the titleLable to be smaller than the size created by adjustFontSizeToFitWidth so the the font size fits in lets say a custom frame like 30x30 while the UIButton's size is 50x50?

    let but:UIButton = UIButton(frame: CGRect(x: 80, y: 80, width: 70, height: 50))
    view.addSubview(but)
    but.backgroundColor = .white
    but.titleLabel?.backgroundColor = .green
    but.setTitle("hello", for: .normal)
    but.setTitleColor(.red, for: .normal)
    //this gives the second image, still having the text uncentered.
    //but.contentVerticalAlignment = .fill
    but.titleLabel?.font = UIFont(name: "WarsawGothicSuExt", size: 60)
    but.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    but.titleLabel?.adjustsFontSizeToFitWidth = true
    but.layoutIfNeeded()

enter image description here

enter image description here

Upvotes: 1

Views: 373

Answers (1)

Code Different
Code Different

Reputation: 93191

You add a content inset which defines a margin between the button's bounds and those of its content:

button.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.layoutIfNeeded()

print(button.bounds)                // (0, 0, 50, 50)
print(button.titleLabel?.bounds)    // (0, 0, 30, 18)

You don't need to call layoutIfNeeded(). It's included here to make the button update itself immediately so we can get the bounding rects.

Upvotes: 1

Related Questions