Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop UITextField from expanding horizontally

I have a UITextField positioned in a view next to a button. It has a trailing constraint of 8 to the button (which has a trailing constraint of 8 to the superview) and when I type long text in it, it simply scrolls along, which is I want. However, in order to retain the text typed in the field if the view is switched to another one (it's in a tab controller), I save the text in a holder variable and when it switches back to that view, I set the text in the field to the saved text.

The problem is that this causes the field to expand horizontally if the text is long enough, sometimes pushing the button off-screen, even with the trailing 8 constraint. I have tried to save the original frame of the field in a holder variable, and then after setting the text, set the frame to the saved original frame like so:

fieldFrame = messageField.frame
println(messageField.frame.width)
messageField.text = holderMessage
println(messageField.frame.width)
messageField.frame = fieldFrame

However, the field still expands, and it printed out 502.0 twice. My current thought is that the frame hasn't registered the change in width after the setting of the text in time for the println, but I'm not sure if this is correct.

Also, I've read some similar questions that suggested using a width constraint. If I use a less than or equal to width constraint on the field, will it still expand if on a device that's thinner? That is to say, since I'm currently using an any width and any height storyboard, it's wider than, say, an iPhone 6. So if I set a less than or equal to width constraint on the current width of the field, it seems possible that the field can still expand on a smaller device and not break that constraint.

Is there a better way to do such a width constraint? If not, how else can I keep the field from expanding and pushing the button offscreen?

like image 938
Technicolor Avatar asked Nov 27 '22 20:11

Technicolor


1 Answers

Here's the problem. The text field has a tendency to size itself horizontally to its contents. The button has a tendency to size itself horizontally to its contents. Thus you have an ambiguity: those tendencies have the same priority, so the runtime doesn't know which one to collapse as the text field's text gets too long.

The solution is to adjust those priorities. You must lower the horizontal compression and hugging priorities for the text field - one point lower should be sufficient. Now the button will have a stronger tendency to match its own size to its contents, and the text field will clip its contents.

enter image description here

like image 56
matt Avatar answered Dec 15 '22 22:12

matt