Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to Adjust UIButton Size based on Text

I have text which can be of variable length. I want to adjust the size of the button to show the text. Some times the text is too much and in those cases I want to limit the size to certain width. How can I do that for UIButton.

enter image description here

Above is the text that is way to long. I want to only show maybe 40 characters.

I am trying to use the range and I get the following:

enter image description here

Final result:

enter image description here

like image 569
john doe Avatar asked Feb 06 '23 05:02

john doe


1 Answers

Using Autolayout, add a width constraint, then set the width constraint's relation to be 'less than or equal' to the constant (max width). The UIButton should auto resize to fit just the text till the max as long as you do not have another fixed width constraint or spacing constraint.

UPDATE: For this to work with different screen sizes, instead of adding a width constraint, add a trailing space (right side) constraint to the superview (for example). Then set that to 'more than or equal' like maybe 20pts. This means the spacing will always adjust itself to be as large as possible without going off screen (width autoresized to fit text).

like image 80
Zayne ZH Avatar answered Feb 13 '23 07:02

Zayne ZH