4

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

Zayne ZH
  • 406
  • 3
  • 9
john doe
  • 9,220
  • 23
  • 91
  • 167

2 Answers2

8

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

Zayne ZH
  • 406
  • 3
  • 9
  • I updated the original question to show the final result. Is there a way to add the "..." in the end instead of automatically adding to the middle. – john doe Sep 02 '16 at 02:59
  • In the attributes inspector of the UIButton there should be a setting lineBreak, just select Truncate Tail instead of Truncate middle – Zayne ZH Sep 02 '16 at 03:01
  • Thanks! One final question. If I make it fixed width let's say 350 then it will still be too big for iPhone 5 and iPhone 4. What can I do in that scenario? – john doe Sep 02 '16 at 14:01
0

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.

Echizzle
  • 3,359
  • 5
  • 17
  • 28