Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set UIButton size by it's title size?

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?

like image 617
Golovanov Dmytrii Avatar asked Feb 16 '18 12:02

Golovanov Dmytrii


Video Answer


1 Answers

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.

like image 199
vacawama Avatar answered Sep 29 '22 14:09

vacawama