简体   繁体   中英

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.

在此处输入图片说明

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:

在此处输入图片说明

Final result:

在此处输入图片说明

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).

I would create a variable to measure the length of the text, then assign the button's frame to that variable multiplied by a certain number. If the text is more than a certain number (40 characters is your case), I would then make the button higher and set the number of lines to 0 so it spills over into the next. If you want to just limit it to 40 altogether there should be a way to prevent any input of over 40 characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM