Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop UITextField resizing when setting text

I have a view setup with 4 UITextFields laid out and constraints setup so that it's looking great on all devices and working as expected. I have an issue where by if I set the text using TextField.text = @" some long text "; or [TextField setText:@"some long text"]; it causes the textfield to expand its width to fit the length of the text and then because of the constraints the other textfields resize too.

How can I stop the textfield resizing ? What I would like is the field to stay the same and the user to be able to just scroll the text If they want to get to the end?

Thanks

like image 498
Gavin Beard Avatar asked Apr 03 '15 22:04

Gavin Beard


1 Answers

You just need to change the constraints. Give the UITextField an explicit internal Width constraint (or use constraints to set or limit its width in some other way) and then things will behave as you desire.

Remember, in general all aspects of a view's size and position must be unambiguously configured by its constraints. Right now, however, your text field has no Width constraint, so its width is based on its text contents (that is, it uses the intrinsic content size to obtain its width). Omitting the Width constraint is not illegal, which is why Interface Builder did not complain when you set up the constraints - but it is legal only because there is an intrinsic content size that supplies a width, and thus it does mean that the width changes if the internal text changes. If that isn't what you want, then don't do that - supply an explicit Width constraint instead.

(Similarly, a text field has an implicit height of 30, which is why you do not have to give it a Height constraint. This height does not change with the text contents, because, unlike a UILabel, a text field does not wrap its text onto multiple lines.)

like image 179
matt Avatar answered Sep 21 '22 16:09

matt