0

I have UITextField and i want allow user to type only up to 4 symbols. But i also want to allow them to erase symbols with keyboard (i mean, delete last and move caret for left. Symbol look like rectangle left arrow with cross on iOS keyboard).

For now i ended up with:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text, text.count < 4 else { return false }
    return true
  }

But i have no idea, how to let users to delete symbols. When text count become 4, i am not allowed to type or do any actions.

Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

4 Answers4

3

From the docs of textField(_:shouldChangeCharactersIn:replacementString:)

When the user deletes one or more characters, the replacement string is empty.

Thus, all you're missing is to check if the replacement string is empty:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.isEmpty || (textField.text?.count ?? 0) < 4
}
fphilipe
  • 9,739
  • 1
  • 40
  • 52
2

use this

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return textField.text!.count + string.count < 5
}
m1sh0
  • 2,236
  • 1
  • 16
  • 21
0

You have to check the length in the should change character in range method. Like following

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let newLength = textField.text.length + (string.length - range.length)

    if newLength <= maxLength {
       return true
    } else {
       return false 
    }
}

Here maxLength is the maximum length of chracters which you want to allow

VishalPethani
  • 854
  • 1
  • 9
  • 17
Waqar Khalid
  • 119
  • 1
  • 12
0

You can use below code to get updated string and compare with that to your length,

func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  // limit to 4 characters
  let characterCountLimit = 4

  // We need to figure out how many characters would be in the string after the change happens
  let startingLength = textFieldToChange.text?.count ?? 0
  let lengthToAdd = string.count
  let lengthToReplace = range.length

  let newLength = startingLength + lengthToAdd - lengthToReplace

  return newLength <= characterCountLimit
}
Ahemadabbas Vagh
  • 492
  • 3
  • 15