I have a UIButton with both a title and an image. The button’s size changes dynamically, but the title text and image inside the button do not resize proportionally to match the button’s size. I want to make sure that both the title and the image adjust their sizes automatically based on the button’s frame to maintain a balanced appearance.
Storyboard button configuration:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
}
Button on the simulator:
I set the title and image for the UIButton, hoping they would resize automatically when the button’s frame changes. However, the title and image remained the same size, not scaling proportionally with the button. I expected both to adjust dynamically to fit the button’s new size, but this didn’t happen.
2
Answers
Here’s a simple solution to ensure your UIButton’s title and image resize dynamically based on the button’s frame:
Explanation:
This approach ensures both the title and image dynamically adjust as the button size changes.
UI components – including controls such as
UIButton
– are rarely a "one size fits all" solution.Buttons do not auto-adjust the font size.
Options are to:
UIButton
and add customization codeHere is a sample custom button control that you may find helpful:
First, we add a
UIImageView
and aUILabel
in a horizontalUIStackView
.Next, we constrain the size of the image view to 60% of the height of the control view (based on your screen-shots).
On
layoutSubviews()
we calculate the font size for the label. Again, based on you screen-shots, it looks like you want the default font size of 17 for a button height of 45. TheUIButton
default is 17-pt for a 35-pt height, so we set the new font size to17.0 * (bounds.height / 35.0)
.We also define this class as
@IBDesignable
with@IBInspectable
title and image so we can lay it out and configure it in Storyboard.Add a
UIView
and set its Custom Class:Set the Image and Title properties:
and we get this at run-time:
This is an example to get you started. See the inline
// comments
for ways you can customize it as desired.