Search code examples
iosswiftautolayoutuitextfielduitextfielddelegate

Narrowing Down UITextField on BackSpace while typing


Using Storyboard, I setup a UITextField and two static UILabels. I setup the constraints so the static labels spread out as user types in the TextField.

       [Label1] [TextField] [Label2]

[Label1] [TextFieldIsGettingFilled] [Label2]

Everything is fine until now. The TextField is getting wider as user types in. However, if the user uses backspace (deletes character), TextField doesn't get narrower. So it becomes like:

[Label1] [TextField         ] [Label2] 

What is the way of detecting backspace and narrow TextFields' width accordingly while user is still typing?


Solution

  • EDIT

    I made an example and this works (increases and decreases according to text):

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

    Source: Resize a UITextField while typing (by using Autolayout)