0

I have a textfield that only accepts numbers, however, it does not accept the delete key so I cannot delete anything once it is typed.

I have tried adding NSCharacters, but I cannot seem to figure out the character for the delete key.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if let x = string.rangeOfCharacter(from: NSCharacterSet.decimalDigits + Character.delete) {
        return true
    } else {
        return false
    }
}

It functions correctly, I just can't backspace due to not accepting it in the code.

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • you can subclass your text field and override deleteBackward method. https://stackoverflow.com/a/29783546/2303865 – Leo Dabus Oct 29 '19 at 14:42
  • @LeoDabus I would stay away from `deleteBackwards` unless you need to detect delete key when the field is empty. `deleteBackwards` did not work correctly until iOS 9-10. – Sulthan Oct 29 '19 at 14:54
  • @Sulthan I don't need to support old iOS versions. But anyway I have tested and it works as expected in all OSs so far – Leo Dabus Oct 29 '19 at 15:06
  • @LeoDabus I am just saying that for most use cases using that method is not needed. Also note that deleting can be done by selecting and cutting. – Sulthan Oct 29 '19 at 15:11
  • Btw you can use Swift 5 character property `isWholeNumber` instead of using range of `CharacterSet` – Leo Dabus Oct 29 '19 at 15:12

1 Answers1

1

You are thinking about it in a wrong way. "Delete" is not a character in this case:

You can simply make an additional check for the replacement string to be empty (deleting = replacing a part of string with "nothing").

if string.isEmpty {
   return true
}

However, your numeric check is not correct and would fail when pasting (e.g. pasting "1a"). Your code is checking that the new string contains a number. The following code checks that there are no other characters than numbers.

return string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil

This check actually works even for empty strings.

Sulthan
  • 128,090
  • 22
  • 218
  • 270