How set UIButton size by it's title size?

Golovanov Dmytrii picture Golovanov Dmytrii · Feb 16, 2018 · Viewed 8.2k times · Source

I have UIButton, which title is dynamic changes. Button size should changes with title size and will be equal title size.

How to do this programmatically in Swift?

Answer

vacawama picture vacawama · Feb 16, 2018

To have your button use its intrinsic content size and automatically resize based upon its text, use Auto Layout to position the button. Only set constraints to position the button and iOS will use the size of the text to determine the width and height of the button.

For example:

let button = UIButton()

// tell it to NOT use the frame
button.translatesAutoresizingMaskIntoConstraints = false

button.setTitle("Hello", for: .normal)
view.addSubview(button)

button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

This also works if you create the button in the Storyboard. Again, only give constraints to place the button and it will resize to accommodate the text.