Jon Setting Jon Setting - 4 months ago 27
iOS Question

Formatting secure text entry by inserting visible spaces

I want the user to enter a Social Security Number in the format ••• •• ••••.
The user types the first 3 numbers, then I append a space manually. Then they enter 2 more numbers and I manually append a space. Of course, even the spaces are being displayed as •. Is there a native way to change this behavior? I am currently using a funky manual implementation of this.

Answer

What if instead of spaces, you use three different text entries? Then when each user enters the first three characters, you jump to the second text entry? When he types two more, you jump to the third text entry.

Here is an example:

EDIT: Now supports backspace (Thanks to @triple-s).

extension ViewController: UITextFieldDelegate {

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        switch textField {
            // Jump forwards
        case self.textField1 where string.characters.count == 3 :
            self.textField2.becomeFirstResponder()
        case self.textField2 where string.characters.count == 2 :
            self.textField3.becomeFirstResponder()

            // Jump backwards
        case self.textField3 where string.characters.count == 0 :
            self.textField2.becomeFirstResponder()
        case self.textField2 where string.characters.count == 0 :
            self.textField1.becomeFirstResponder()
        default :
            break
        }

        return true
    }
}
Comments