Gavin Beard
Gavin Beard

Reputation: 199

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

Upvotes: 6

Views: 5340

Answers (2)

Fattie
Fattie

Reputation: 12582

There are some odd situations where the solver rules are hard to guess. Eg

  • make an outer wrapper UIView
  • put a text field inside it, and
  • add four constraints to the wrapper
  • fix the width of the wrapper to say 200 using the intrinsic content size
  • put some of those in a horizontal stack view which sizes itself (perhaps by being in a scroll view)

In many cases it will STILL resize (ie both the text field and wrapper) when you type long text in the text field.

In such cases one solution can be

    setContentCompressionResistancePriority(.required, for: .horizontal)
    setContentHuggingPriority(.required, for: .horizontal)

applied to the wrapper and/or the text field itself.

Upvotes: 0

matt
matt

Reputation: 534903

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

Upvotes: 14

Related Questions