Detect backspace Event in UITextField

后端 未结 11 608
自闭症患者
自闭症患者 2020-12-04 16:35

I am searching for solutions on how to capture a backspace event, most Stack Overflow answers are in Objective-C but I need on Swift language.

First I have set deleg

11条回答
  •  无人及你
    2020-12-04 17:16

    I prefer subclassing UITextField and overriding deleteBackward() because that is much more reliable than the hack of using shouldChangeCharactersInRange:

    class MyTextField: UITextField {
        override public func deleteBackward() {
            if text == "" {
                 // do something when backspace is tapped/entered in an empty text field
            }
            // do something for every backspace
            super.deleteBackward()
        }
    }
    

    The shouldChangeCharactersInRange hack combined with an invisible character that is placed in the text field has several disadvantages:

    • with a keyboard attached, one can place the cursor before the invisible character and the backspace isn't detected anymore,
    • the user can even select that invisible character (using Shift Arrow on a keyboard or even by tapping on the caret) and will be confused about that weird character,
    • the autocomplete bar offers weird choices as long as there's only this invisible character,
    • Asian language keyboards that have candidate options based on the text field's text will be confused,
    • the placeholder isn't shown anymore,
    • the clear button is displayed even when it shouldn't for clearButtonMode = .whileEditing.

    Of course, overriding deleteBackward() is a bit inconvenient due to the need of subclassing. But the better UX makes it worth the effort!

    And if subclassing is a no-go, e.g. when using UISearchBar with its embedded UITextField, method swizzling should be fine, too.

提交回复
热议问题