Oleksandr Fisun
Oleksandr Fisun

Reputation: 193

Change UITextField width dynamically depends of content

I have the same issue as here: Resize a UITextField while typing (by using Autolayout)

But It was resolved with UITextView and not with UITextField.

This code doesn't help:

func textFieldDidChange(sender: UITextField) {
    sender.invalidateIntrinsicContentSize()
}

I have UITextField(red background) and use AutoLayout with StackView:

enter image description here

and constraints:

enter image description here

but UITextField change it width only when it is resignFirstResponder. Could you give me please any advice about the issue? I'm new in Swift and iOS Development.

Upvotes: 2

Views: 6071

Answers (3)

Aditya Deshmane
Aditya Deshmane

Reputation: 4722

This works for UITextField. In my case I wanted the font to be of the same size. I set textField width constraint to >= 10 and it just works fine on iOS 9, 10, 11.

For iOS 11 this even works while editing text.

To make this work while editing text on iOS 9 and 10, I handled one more method by registering for a textDidChange event.

//Swift 3 Sample

//In viewDidLoad
adjustableTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)


 @objc func textFieldDidChange(_ textField: UITextField) {
    adjustableTextField.resignFirstResponder()
    adjustableTextField.becomeFirstResponder()
}

Upvotes: 1

paulvs
paulvs

Reputation: 12053

UITextField does not call your method textFieldDidChange(_:) when it changes content (it is not part of UITextFieldDelegate). You should use textField(_:shouldChangeCharactersInRange:replacementString:) instead.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    textField.invalidateIntrinsicContentSize()
    return true
}

Upvotes: 3

Adam H.
Adam H.

Reputation: 680

To do this using Autolayout, you will need a constraint for the width of the text field. Then, when the text changes, calculate the desired width and set the constant property on the constraint to that value. Lastly, you will need to call layoutIfNeeded() on the parent view.

Upvotes: 1

Related Questions