Search code examples
iosswiftuitextfield

How to check if textfield has more than one letter in Swift?


I'm working on a text field in Swift and what I'm about to implement is that disabling the navigation button unless there is 0 character in the text field and adding the delete button on the text field if there is more than 1 letter on the text field, like an iOS default calendar app.

The bar button item "Add" is disabled when there is no letter in the title text field.

enter image description here

Enable the "Add" button and show the delete button when there is 1+ letter in the Title text field.

enter image description here

I took a look at the text field delegate methods and I think I can implement the one I'm trying to by using shouldChangeCharactersIn method (?)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // check if there is a letter in the text field
    // if there is, enable the Add button and show delete icon
    // if there is not, disable the add button and hide the delete icon
    return true
}

I was wondering if there are other methods to implement this functionality? I think whenever type / delete a letter on the text field, the function above will be called everytime, so I was wondering if there are other ways to implement this stuff easily.


Solution

  •  func textFieldDidChangeSelection(_ textField: UITextField) {
        validateTextField(text:textField.tex)
    }
    

    your method shouldChangeCharactersIn is not working properly sometimes so can use this method make a function that take text and disable and enable nav bar and delete button like

    func validateTextField(text:String) {
      if text.count > 1 {
        textField.clearButtonMode = .whileEditing
      } else if text.count <= 1 {
         textField.clearButtonMode = .never
      } else if text.count < 1 {
         navigationItem.leftBarButtonItem.tintColor = .lightGray
      }